|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int N, M; |
| 7 | + static int[][] grid; |
| 8 | + static boolean[][] visited; |
| 9 | + static int[] dx = {-1, -1, -1, 0, 0, 1, 1, 1}; |
| 10 | + static int[] dy = {-1, 0, 1, -1, 1, -1, 0, 1}; |
| 11 | + |
| 12 | + public static void main(String[] args) throws IOException { |
| 13 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 14 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 15 | + |
| 16 | + N = Integer.parseInt(st.nextToken()); |
| 17 | + M = Integer.parseInt(st.nextToken()); |
| 18 | + |
| 19 | + grid = new int[N][M]; |
| 20 | + visited = new boolean[N][M]; |
| 21 | + |
| 22 | + for (int i = 0; i < N; i++) { |
| 23 | + st = new StringTokenizer(br.readLine()); |
| 24 | + for (int j = 0; j < M; j++) { |
| 25 | + grid[i][j] = Integer.parseInt(st.nextToken()); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + int count = 0; |
| 30 | + for (int i = 0; i < N; i++) { |
| 31 | + for (int j = 0; j < M; j++) { |
| 32 | + if (!visited[i][j] && isPeak(i, j)) { |
| 33 | + count++; |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + System.out.println(count); |
| 39 | + } |
| 40 | + |
| 41 | + static boolean isPeak(int x, int y) { |
| 42 | + ArrayDeque<int[]> queue = new ArrayDeque<>(); |
| 43 | + List<int[]> component = new ArrayList<>(); |
| 44 | + |
| 45 | + queue.offer(new int[]{x, y}); |
| 46 | + visited[x][y] = true; |
| 47 | + component.add(new int[]{x, y}); |
| 48 | + |
| 49 | + int height = grid[x][y]; |
| 50 | + boolean isPeak = true; |
| 51 | + |
| 52 | + while (!queue.isEmpty()) { |
| 53 | + int[] cur = queue.poll(); |
| 54 | + |
| 55 | + for (int i = 0; i < 8; i++) { |
| 56 | + int nx = cur[0] + dx[i]; |
| 57 | + int ny = cur[1] + dy[i]; |
| 58 | + |
| 59 | + if (nx < 0 || nx >= N || ny < 0 || ny >= M) continue; |
| 60 | + |
| 61 | + if (grid[nx][ny] > height) { |
| 62 | + isPeak = false; |
| 63 | + } |
| 64 | + |
| 65 | + if (!visited[nx][ny] && grid[nx][ny] == height) { |
| 66 | + visited[nx][ny] = true; |
| 67 | + queue.offer(new int[]{nx, ny}); |
| 68 | + component.add(new int[]{nx, ny}); |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + return isPeak; |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +``` |
0 commit comments