#include <iostream> #include <vector> #include <queue> using namespace std; int N, M; // 행, 열 int check[300][300]; int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // 상하좌우 queue <pair<int, int>> tmp; // 동서남북의 0 개수 세고 빙산 녹이기 void remove_iceberg(int x, int y, vector<vector<int>> &iceberg) { int zero = 0; // 0 개수 for(int i=0; i<4; i++) { int nx = x + dir[i][0]; int ny = y + dir[i][1]; if(nx < 0 || ny < 0 || nx >= N || ny >= M) continue; if(check[nx][ny]) continue; if(iceberg[nx][ny] == 0) { zero++; } } if(zero > 0) { iceberg[x][y] -= zero; if(iceberg[x][y] < 0) iceberg[x][y] = 0; } } // 연결된 빙산 개수 찾기 void count_iceberg(vector<vector<int>> iceberg) { while(!tmp.empty()) { int x = tmp.front().first; int y = tmp.front().second; tmp.pop(); for(int i=0; i<4; i++) { int nx = x + dir[i][0]; int ny = y + dir[i][1]; if(nx < 0 || ny < 0 || nx >= N || ny >= M) continue; if(iceberg[nx][ny] == 0 || check[nx][ny]) continue; check[nx][ny] = 1; tmp.push({nx, ny}); } } } int main() { // 1. 빙산 정보 입력 받기 cin >> N >> M; vector <vector<int>> iceberg(N, vector<int>(M)); // 빙산 for(int i=0; i<N; i++) { for(int j=0; j<M; j++) { cin >> iceberg[i][j]; } } int year = 0; while(1) { // 녹일 빙산 찾기 for(int i=0; i<N; i++) { for(int j=0; j<M; j++) { if(iceberg[i][j] != 0) { // 남아있다면 // 2. 빙산 녹이기 check[i][j] = 1; remove_iceberg(i, j, iceberg); } } } fill(&check[0][0], &check[N][0], 0); // 3. 연결된 빙산 개수 세기 int cnt = 0; for(int i=0; i<N; i++) { for(int j=0; j<M; j++) { if(iceberg[i][j] != 0 && check[i][j] == 0) { cnt++; check[i][j] = 1; tmp.push({i, j}); count_iceberg(iceberg); } } } year++; if(cnt >= 2) { cout << year << endl; exit(0); } if(cnt == 0) { cout << 0; exit(0); } } return 0; }
→ 전체적으로 실수를 너무 많이 한 것 같다. 너무 급하게 풀지 말고 천천히 생각해보며 실수 줄이기 !