#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
const int MAX = 51;
int n, l, r;
int map[MAX][MAX];
bool possible = false;
int visited[MAX][MAX];
struct Move {
int x, y;
};
Move mv[4] = { {1,0}, {0,1}, {-1,0}, {0,-1} };
void bfs(int i, int j) {
int sum = 0;
queue<pair<int, int>> q;
vector<pair<int, int>> temp;
q.push(make_pair(i, j));
temp.push_back(make_pair(i, j));
sum += map[i][j];
visited[i][j] = 1;
while (!q.empty()) {
int currenti = q.front().first;
int currentj = q.front().second;
q.pop();
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 < n) {
int minus = abs(map[currenti][currentj] - map[movei][movej]);
if (visited[movei][movej] == -1 && minus >= l && minus <= r) {
q.push(make_pair(movei, movej));
temp.push_back(make_pair(movei, movej));
visited[movei][movej] = 1;
sum += map[movei][movej];
}
}
}
}
if (temp.size() > 1)
possible = true;
int value = sum / temp.size();
for (int k = 0; k < temp.size(); k++) {
map[temp[k].first][temp[k].second] = value;
}
return;
}
int main(void) {
int answer = 0;
cin >> n >> l >> r;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> map[i][j];
}
}
do {
possible = false;
memset(visited, -1, sizeof(visited));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (visited[i][j] == -1)
bfs(i, j);
}
}
answer++;
} while (possible);
cout << answer-1 << endl;
return 0;
}
'백준 알고리즘 > BFS' 카테고리의 다른 글
백준 구슬 탈출 2 C++ (0) | 2019.10.18 |
---|---|
백준 연구소3 C++ (0) | 2019.10.18 |
백준 5427번 C++ (0) | 2019.08.21 |
백준 2251번 C++ (0) | 2019.08.20 |
백준 1325번 C++ (0) | 2019.08.20 |