슈콩

[BOJ] 백준 2468 안전 영역 본문

Algorithms/Baekjoon

[BOJ] 백준 2468 안전 영역

shukong 2025. 9. 30. 13:07

[문제]

https://www.acmicpc.net/problem/2468

 

 

[소스 코드]

import java.io.*;
import java.util.*;

public class Main {
	static int n,result = 0;
	static int[][] map;
	static int[] dr = {-1,1,0,0};
	static int[] dc = {0,0,-1,1};
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		n = Integer.parseInt(br.readLine());
		map = new int[n][n];
		int max = Integer.MIN_VALUE;
		int min = Integer.MAX_VALUE;
		for(int i=0;i<n;i++) {
			st = new StringTokenizer(br.readLine());
			for(int j=0;j<n;j++) {
				map[i][j] = Integer.parseInt(st.nextToken());
				max = Math.max(max, map[i][j]);
				min = Math.min(min, map[i][j]);
			}
		}
		for(int h=min-1;h<max;h++) {
			result = Math.max(result,bfs(h));
		}
		System.out.println(result);
	}
	private static int bfs(int h) {
		Queue<int[]> q = new LinkedList<>();
		boolean[][] visit = new boolean[n][n];
		int cnt = 0;
		for(int i=0;i<n;i++) {
			for(int j=0;j<n;j++) {
				if(map[i][j]>h && !visit[i][j]) {
					visit[i][j] = true;
					q.offer(new int[] {i,j});
					cnt++;
					while(!q.isEmpty()) {
						int[] curr = q.poll();
						for(int d=0;d<4;d++) {
							int nr = curr[0] + dr[d];
							int nc = curr[1] + dc[d];
							if(nr<0 || nr>=n || nc<0 || nc>=n || visit[nr][nc]) continue;
							if(map[nr][nc]>h) {
								visit[nr][nc] = true;
								q.offer(new int[] {nr,nc});
							}
						}
					}
				}
			}
		}
		return cnt;
	}
}

'Algorithms > Baekjoon' 카테고리의 다른 글

[BOJ] 백준 9205 맥주 마시면서 걸어가기  (0) 2025.09.30
[BOJ] 백준 2573 빙산  (0) 2025.09.30
[BOJ] 백준 5014 스타트링크  (0) 2025.09.30
[BOJ] 백준 1697 숨바꼭질  (0) 2025.09.30
[BOJ] 백준 7569 토마토  (0) 2025.09.29