|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class boj1245 { |
| 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 N, M, answer; |
| 12 | + static int[][] map; |
| 13 | + static boolean[][] visited, top; |
| 14 | + static int[][] dir = {{1,0}, {0,1}, {0,-1}, {-1,0}, {-1,1}, {-1,-1}, {1,1}, {1,-1}}; |
| 15 | + public static void main(String[] args) throws Exception { |
| 16 | + nextLine(); |
| 17 | + N = nextInt(); |
| 18 | + M = nextInt(); |
| 19 | + map = new int[N][M]; |
| 20 | + top = new boolean[N][M]; |
| 21 | + for (int i = 0; i < N; i++) { |
| 22 | + nextLine(); |
| 23 | + for (int j = 0; j < M; j++) map[i][j] = nextInt(); |
| 24 | + } |
| 25 | + for (int i = 0; i < N; i++) { |
| 26 | + for (int j = 0; j < M; j++) { |
| 27 | + if (map[i][j] == 0 || top[i][j]) continue; |
| 28 | + bfs(i, j); |
| 29 | + } |
| 30 | + } |
| 31 | + System.out.println(answer); |
| 32 | + } |
| 33 | + static void bfs(int y, int x) { |
| 34 | + Queue<Pos> q = new LinkedList<>(); |
| 35 | + boolean[][] visited = new boolean[N][M]; |
| 36 | + LinkedList<Pos> topList = new LinkedList<>(); |
| 37 | + q.add(new Pos(y, x)); |
| 38 | + visited[y][x] = true; |
| 39 | + while (!q.isEmpty()) { |
| 40 | + Pos cur = q.poll(); |
| 41 | + for (int[] d : dir) { |
| 42 | + int ny = cur.y + d[0]; |
| 43 | + int nx = cur.x + d[1]; |
| 44 | + if (ny < 0 || ny >= N || nx < 0 || nx >= M || visited[ny][nx]) continue; |
| 45 | + visited[ny][nx] = true; |
| 46 | + if (map[ny][nx] > map[cur.y][cur.x]) return; |
| 47 | + else if (map[ny][nx] == map[cur.y][cur.x]) { |
| 48 | + q.add(new Pos(ny, nx)); |
| 49 | + topList.add(new Pos(ny, nx)); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + for (Pos pos : topList) { |
| 54 | + top[pos.y][pos.x] = true; |
| 55 | + } |
| 56 | + answer++; |
| 57 | + } |
| 58 | + |
| 59 | + static class Pos { |
| 60 | + int y, x; |
| 61 | + public Pos(int y, int x) { |
| 62 | + this.y = y; |
| 63 | + this.x = x; |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | +``` |
0 commit comments