#include <iostream>
#include <string>
#include <queue>
#include <cstring>
using namespace std;
const int MAX = 301;
int n, m;
int map[MAX][MAX];
queue<pair<int, int>> q;
int visited[MAX][MAX];
int copys[MAX][MAX];
struct Move {
int x, y;
};
Move mv[4] = { {1,0}, {-1,0} ,{0,1}, {0,-1} };
bool divide() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (copys[i][j] > 0 && visited[i][j] == -1)
return true;
}
}
return false;
}
void bfs() {
while (!q.empty()) {
int currenti = q.front().first;
int currentj = q.front().second;
q.pop();
visited[currenti][currentj] = 1;
if (map[currenti][currentj] == 0)
continue;
for (int k = 0; k < 4; k++) {
int movei = currenti + mv[k].x;
int movej = currentj + mv[k].y;
if (movei >= 0 && movei < n && movej >= 0 && movej < m) {
if (copys[movei][movej] == 0 && map[currenti][currentj] >=1)
map[currenti][currentj] -= 1;
if (map[movei][movej] != 0 && visited[movei][movej] == -1) {
q.push(make_pair(movei, movej));
visited[movei][movej] = 1;
}
}
}
}
return;
}
int main(void) {
int counts,answer = 0;
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> map[i][j];
}
}
while (true) {
counts = 0;
memset(visited, -1, sizeof(visited));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
copys[i][j] = map[i][j];
if (map[i][j] != 0 && counts == 0) {
q.push(make_pair(i, j));
counts++;
}
}
}
if (q.size() == 0) {
answer = 0;
break;
}
bfs();
if (divide())
break;
answer++;
}
cout << answer << endl;
return 0;
}
'백준 알고리즘 > BFS' 카테고리의 다른 글
백준 2146번 C++ (0) | 2019.08.17 |
---|---|
백준 1963번 C++ (0) | 2019.08.16 |
백준 2206번 C++ (0) | 2019.08.15 |
백준 3055번 C++ (0) | 2019.08.14 |
백준 1707번 C++ (0) | 2019.08.14 |