[BFS / DFS] [백준 / 2468 ] 실버1 - 안전영역 (java/자바)



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import newboj.boj_2667.Point;
public class Main {
static int[][] map;
static boolean[][] isVisited;
static int low = Integer.MAX_VALUE;
static int high = Integer.MIN_VALUE;
static int[] dy = new int[]{-1, 1, 0, 0};
static int[] dx = new int[]{0, 0, 1, -1};
static int N;
static int resultCount = 0;
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(r.readLine());
map = new int[N][N];
isVisited = new boolean[N][N];
for (int i = 0; i < N; i++) {
map[i] = Arrays.stream(r.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
low = Math.min(low, map[i][j]);
high = Math.max(high, map[i][j]);
}
}
for (int k = low-1; k < high; k++) {
int count=0;
isVisited = new boolean[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (!isVisited[i][j] && map[i][j] > k) {
dfs(new Point(i, j), k); // 물의 높이 k를 dfs에 전달
count++;
}
}
}
resultCount = Math.max(resultCount,count);
}
System.out.println(resultCount);
}
static void dfs(Point point,int k) {
isVisited[point.y][point.x] = true;
for (int i = 0; i < 4; i++) {
int nextY = point.y + dy[i];
int nextX = point.x + dx[i];
if (!(0 <= nextY && nextY < N && 0 <= nextX && nextX < N)) {
continue;
}
if (map[nextY][nextX] <=k) {
continue;
}
if (isVisited[nextY][nextX] == true) {
continue;
}
dfs(new Point(nextY, nextX),k);
}
}
static class Point {
int y;
int x;
Point(int y, int x) {
this.y = y;
this.x = x;
}
}
}
static void bfs(Point start, int k) {
Queue<Point> queue = new LinkedList<>();
queue.add(start);
isVisited[start.y][start.x] = true;
while (!queue.isEmpty()) {
Point current = queue.poll();
for (int i = 0; i < 4; i++) {
int nextY = current.y + dy[i];
int nextX = current.x + dx[i];
if (0 <= nextY && nextY < N && 0 <= nextX && nextX < N) {
if (!isVisited[nextY][nextX] && map[nextY][nextX] > k) {
isVisited[nextY][nextX] = true;
queue.add(new Point(nextY, nextX));
}
}
}
}
물에 잠기지 않는 안전한 영역의 최대 개수를 찾는 이 문제의 경우, DFS와 BFS 모두 유효한 선택입니다. DFS는 코드의 간결성과 깊이 있는 탐색에 유리한 반면, BFS는 넓은 영역의 체계적 탐색과 동일 레벨의 탐색에 더 효과적일 수 있습니다.