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