본문 바로가기
백준 알고리즘/BFS

백준 2468번 C++

by paysmile 2019. 8. 10.

#include <iostream>
#include <queue>
#include <cstring>

using namespace std;
const int MAX = 101;
int n;
int height[MAX][MAX];
int visited[MAX][MAX];
struct Move {
	int x, y;
};
Move mv[4] = { {1,0},{-1,0},{0,1},{0,-1} };

void bfs(int i, int j, int k) {
	queue<pair<int, int>> q;
	q.push(make_pair(i, j));
	visited[i][j] = 1;

	while (!q.empty()) {
		int currenti = q.front().first;
		int currentj = q.front().second;
		q.pop();

		for (int index = 0; index < 4; index++) {
			int movei = currenti + mv[index].x;
			int movej = currentj + mv[index].y;

			if (movei >= 0 && movei < n && movej >= 0 && movej <n && height[movei][movej] > k && visited[movei][movej] == -1) {
				visited[movei][movej] = 1;
				q.push(make_pair(movei, movej));
			}
		}
	}
}

int main(void) {
	int maxheight = 0;
	int answer = 1;

	cin >> n;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			cin >> height[i][j];
			maxheight = max(maxheight, height[i][j]);
		}
	}
	for (int k = 1; k < maxheight; k++) {
		memset(visited, -1, sizeof(visited));
		int safearea = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (height[i][j] > k && visited[i][j] == -1) {
					bfs(i, j, k);
					safearea++;
				}
			}
		}
		answer = max(answer, safearea);
	}
	cout << answer << endl;
	return 0;
}

'백준 알고리즘 > BFS' 카테고리의 다른 글

백준 2589번 C++  (0) 2019.08.12
백준 7569번 C++  (0) 2019.08.10
백준 11403번 C++  (0) 2019.08.08
백준 1012번 C++  (0) 2019.08.08
백준 7576번 C++  (0) 2019.08.08