https://www.acmicpc.net/problem/2573
bfs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | #include <iostream> #include <queue> using namespace std; int map[300][300] = {0}; int dx[4] = {1,-1,0,0}; int dy[4] = {0,0,1,-1}; int n,m; bool bfs_chk(){ int cnt = 0; bool visited[300][300] = {0}; queue<pair<int,int> > q; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(cnt >=2) return true; if(visited[i][j] || map[i][j] == 0) continue; cnt+=1; q.push({i,j}); visited[i][j] = 1; while(!q.empty()){ int x= q.front().second, y = q.front().first; q.pop(); for(int k = 0; k < 4; k++){ int xx = x + dx[k], yy = y + dy[k]; if(yy >= n || yy < 0 || xx >= m || xx < 0) continue; if(map[yy][xx] == 0 || visited[yy][xx]) continue; q.push({yy,xx}); visited[yy][xx] = 1; } } } } return false; } bool chk_zero(){ for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(map[i][j] != 0) return false; } } return true; } int main(){ int y = 0; int m_map[300][300] = {0}; cin >> n >> m; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++) cin >> map[i][j]; } while(1){ if(chk_zero()){ cout << 0; break;} if(bfs_chk()){cout << y; break;} y+=1; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(map[i][j] != 0){ int zero_cnt = 0; for(int k = 0; k < 4; k++){ int x = j + dx[k] , y = i + dy[k]; if(map[y][x] == 0) zero_cnt+=1; } m_map[i][j] = zero_cnt; } } } for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(map[i][j] != 0){ map[i][j] -= m_map[i][j]; if(map[i][j] < 0) map[i][j] = 0; } } } } } | cs |
반응형
'프로그래밍 > 문제풀이' 카테고리의 다른 글
[dfs] 백준 2644 촌수계산 (0) | 2019.03.27 |
---|---|
[dfs] 백준 9903 로또 (0) | 2019.03.27 |
[bfs, dfs] 백준 2667 단지번호붙이기 (0) | 2019.03.24 |
[dfs] 백준 2606 바이러스 (0) | 2019.03.22 |
[bfs] 백준 7569 토마토 (0) | 2019.03.22 |