|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class boj1113 { |
| 6 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + static StringTokenizer st; |
| 8 | + static void nextLine() throws Exception { st = new StringTokenizer(br.readLine()); } |
| 9 | + static int nextInt() { return Integer.parseInt(st.nextToken()); } |
| 10 | + |
| 11 | + static int[][] dir = new int[][] {{1,0}, {-1,0}, {0,1}, {0,-1}}; |
| 12 | + static int N, M, answer; |
| 13 | + static int[][] land; |
| 14 | + static boolean[][] visited; |
| 15 | + static Queue<int[]> q = new LinkedList<>(); |
| 16 | + public static void main(String[] args) throws Exception { |
| 17 | + nextLine(); |
| 18 | + N = nextInt(); |
| 19 | + M = nextInt(); |
| 20 | + int min = Integer.MAX_VALUE; |
| 21 | + int max = Integer.MIN_VALUE; |
| 22 | + answer = 0; |
| 23 | + land = new int[N][M]; |
| 24 | + visited = new boolean[N][M]; |
| 25 | + for (int i = 0; i < N; i++) { |
| 26 | + String line = br.readLine(); |
| 27 | + for (int j = 0; j < M; j++) { |
| 28 | + land[i][j] = Integer.parseInt(line.substring(j, j+1)); |
| 29 | + min = Math.min(min, land[i][j]); |
| 30 | + max = Math.max(max, land[i][j]); |
| 31 | + } |
| 32 | + } |
| 33 | + for (int h = min; h < max; h++) { |
| 34 | + for (int i = 1; i < N-1; i++) { |
| 35 | + for (int j = 1; j < M-1; j++) { |
| 36 | + if (land[i][j] == h) { |
| 37 | + answer += bfs(i, j, h); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + System.out.println(answer); |
| 43 | + } |
| 44 | + |
| 45 | + static int bfs(int y, int x, int h) { |
| 46 | + q.clear(); |
| 47 | + q.add(new int[] {y, x}); |
| 48 | + int cnt = 1; |
| 49 | + boolean flag = true; |
| 50 | + land[y][x] = h + 1; |
| 51 | + while (!q.isEmpty()) { |
| 52 | + int[] cur = q.poll(); |
| 53 | + for (int[] d : dir) { |
| 54 | + int ny = cur[0] + d[0]; |
| 55 | + int nx = cur[1] + d[1]; |
| 56 | + if (ny < 0 || ny >= N || nx < 0 || nx >= M || land[ny][nx] < h) { |
| 57 | + flag = false; |
| 58 | + continue; |
| 59 | + } |
| 60 | + if (h != land[ny][nx]) continue; |
| 61 | + land[ny][nx] = h + 1; |
| 62 | + cnt++; |
| 63 | + q.offer(new int[] {ny, nx}); |
| 64 | + } |
| 65 | + } |
| 66 | + if (flag) return cnt; |
| 67 | + return 0; |
| 68 | + } |
| 69 | +} |
| 70 | +``` |
0 commit comments