알고리즘

[알고리즘] 백준 17144 - 미세먼지 안녕!

blueberrysoda 2024. 7. 16. 23:45
#include <iostream>
#include <vector>
using namespace std;

int R, C, T;
int V[51][51];
int tmp[51][51];
int Dir[4][2] = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};
int UY, DY;
bool flag;

void move(){    
    for(int i=0; i<R; i++){
        for(int j=0; j<C; j++){
            if(V[i][j] == 0 || V[i][j] == -1) continue;
            for(int d=0; d<4; d++){
                int y = i + Dir[d][0];
                int x = j + Dir[d][1];
                if(y < 0 || x < 0 || y >= R || x >= C || V[y][x] == -1) continue;
                tmp[y][x] += V[i][j] / 5;
                tmp[i][j] -= V[i][j] / 5;
            }
        }
    }
    
    for(int i=0; i<R; i++){
        for(int j=0; j<C; j++){
            V[i][j] += tmp[i][j];
            tmp[i][j] = 0;
        }
    }

    return;
}

void clean(){
    for(int i=UY-1; i>0; i--){
        V[i][0] = V[i-1][0];
    }
    for(int i=0; i<C-1; i++){
        V[0][i] = V[0][i+1];
    }
    for(int i=0; i<UY; i++){
        V[i][C-1] = V[i+1][C-1]; 
    }
    for(int i=C-1; i>1; i--){
        V[UY][i] = V[UY][i-1];
    }
    V[UY][1] = 0;

    for(int i=DY+1; i<R-1; i++){
        V[i][0] = V[i+1][0];
    }
    for(int i=0; i<C-1; i++){
        V[R-1][i] = V[R-1][i+1];
    }
    for(int i=R-1; i>DY; i--){
        V[i][C-1] = V[i-1][C-1];
    }
    for(int i=C-1; i>1; i--){
        V[DY][i] = V[DY][i-1];
    }
    V[DY][1] = 0;
    return;
}

void solve(){
    move();
    clean();
    return;
}

int main(){
    cin >> R >> C >> T;
    for(int i=0; i<R; i++){
        for(int j=0; j<C; j++){
            cin >> V[i][j];
            if(V[i][j] == -1){
                if(flag == false){
                    UY = i;
                    flag = true;
                }
                else{
                    DY = i;
                }
            }
        }
    }

    while(T--){
        solve();
    }

    int Ans = 2;
    for(int i=0; i<R; i++){
        for(int j=0; j<C; j++){
            Ans += V[i][j];
        }
    }
    cout << Ans << "\n";

    return 0;
}