Gidhub BE Developer

[BOJ] 톱니바퀴

2018-04-14
goodGid

Problem

Problem URL : 톱니바퀴


[1] Answer Code (18. 04. 14)



#include<iostream>
#include<cstring>
using namespace std;

int idx,dir;
int visit[5];
int a[5][9];
int b[5][9];


void solve(int idx, int dir){
    if( idx > 4 || idx < 1 || visit[idx]==1) return ;
    else {
        visit[idx] = 1;
        if( dir == 1 ){
            for(int i=1; i<=8; i++) b[idx][ i % 8 + 1] = a[idx][i];
        }
        else {
            for(int i=2; i<=8; i++) b[idx][ i-1 ] = a[idx][i];
            b[idx][8] = a[idx][1];
        }
        
        //Right
        if( idx+1 <= 4){
            if( a[idx][3] == a[idx+1][7] ){
                for(int i=idx+1; i<=4; i++) for(int j=1; j<=9; j++) b[i][j] = a[i][j];
            }
            else {
                solve(idx+1, dir * -1);
            }
        }
        
        
        //Left
        if( idx-1 >= 1){
            if( a[idx][7] == a[idx-1][3]){
                for(int i=idx-1; i>0; i--) for(int j=1; j<=9; j++) b[i][j] = a[i][j];
            }
            else {
                solve(idx-1, dir * -1);
            }
        }
        
        visit[idx] = 0;
    } // End of else
    
}



int main(){
    for(int i=1; i<=4; i++)
        for(int j=1; j<=8; j++)
            scanf("%1d",&a[i][j]);
    
    int tc;
    cin >> tc;
    
    for(int i=1; i<=tc; i++){
        cin >> idx >> dir;
        solve(idx, dir);
        for(int i=1; i<=4; i++) for(int j=1; j<=8; j++) a[i][j] = b[i][j];
    }
    
    int cnt=0;
    if(b[1][1] == 1) cnt += 1;
    if(b[2][1] == 1) cnt += 2;
    if(b[3][1] == 1) cnt += 4;
    if(b[4][1] == 1) cnt += 8;
    cout << cnt << endl;
    return 0;
}







[2] Answer Code (18. 04. 14)




#include<iostream>
using namespace std;

int idx,dir;
int visit[5];
int a[5][9];

void solve(int idx, int dir){
    visit[idx] = 1;
    
    //Right
    if( idx+1 <= 4 && a[idx][3] != a[idx+1][7] && !visit[idx+1]){
        solve(idx+1, dir * -1);
    }
    
    //Left
    if( idx-1 >= 1 && a[idx][7] != a[idx-1][3] && !visit[idx-1] ){
        solve(idx-1, dir * -1);
    }
    
    visit[idx] = 0;
    
    int tmp;
    if( dir == 1 ){
        tmp = a[idx][8];
        for(int i=7; i>0; i--)
            a[idx][i+1] = a[idx][i];
        a[idx][1] = tmp;
    }
    else {
        tmp = a[idx][1];
        for(int i=1; i<=7; i++)
            a[idx][i] = a[idx][i+1];
        a[idx][8] = tmp;
    }
}

int main(){
    for(int i=1; i<=4; i++)
        for(int j=1; j<=8; j++)
            scanf("%1d",&a[i][j]);
    
    int tc;
    cin >> tc;
    
    for(int i=1; i<=tc; i++){
        cin >> idx >> dir;
        solve(idx, dir);
    }
    
    int cnt=0;
    if(a[1][1] == 1) cnt += 1;
    if(a[2][1] == 1) cnt += 2;
    if(a[3][1] == 1) cnt += 4;
    if(a[4][1] == 1) cnt += 8;
    cout << cnt << endl;
    return 0;
}





Code Review

[1],[2] Answer Code (18. 04. 14)

  • [1]코드를 이 코드를 보고 [2]으로 Refactoring

  • 굉장히 재밌는 문제이다.


Index