|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + |
| 7 | + static int n, m, res; |
| 8 | + static int[][] map; |
| 9 | + static boolean[][] visited; |
| 10 | + static int[] dx = {-1, 1, 0, 0}; |
| 11 | + static int[] dy = {0, 0, -1, 1}; |
| 12 | + |
| 13 | + public static void main(String[] args) throws IOException { |
| 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 + 2][m + 2]; |
| 21 | + |
| 22 | + for (int i = 1; i <= n; i++) { |
| 23 | + String s = br.readLine(); |
| 24 | + for (int j = 1; j <= m; j++) { |
| 25 | + map[i][j] = Integer.parseInt(String.valueOf(s.charAt(j-1))); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + for (int k = 2; k <= 9; k++) { |
| 30 | + visited = new boolean[n + 2][m + 2]; |
| 31 | + for (int i = 1; i <= n; i++) { |
| 32 | + for (int j = 1; j <= m; j++) { |
| 33 | + if(visited[i][j]||map[i][j]>=k) |
| 34 | + continue; |
| 35 | + res += bfs(i, j, k); |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + System.out.println(res); |
| 40 | + } |
| 41 | + |
| 42 | + static int bfs(int x, int y, int height) { |
| 43 | + Queue<int[]> q = new ArrayDeque<>(); |
| 44 | + List<int[]> list = new ArrayList<>(); |
| 45 | + boolean ground = false; |
| 46 | + int water = 0; |
| 47 | + q.add(new int[]{x, y}); |
| 48 | + list.add(new int[]{x, y}); |
| 49 | + |
| 50 | + while (!q.isEmpty()) { |
| 51 | + int[] cur = q.poll(); |
| 52 | + for (int d = 0; d < 4; d++) { |
| 53 | + int nx = cur[0] + dx[d]; |
| 54 | + int ny = cur[1] + dy[d]; |
| 55 | + if (map[nx][ny] == 0) { |
| 56 | + ground=true; |
| 57 | + continue; |
| 58 | + } |
| 59 | + if (!visited[nx][ny] && map[nx][ny] < height) { |
| 60 | + q.add(new int[]{nx, ny}); |
| 61 | + list.add(new int[]{nx, ny}); |
| 62 | + visited[nx][ny] = true; |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + if(ground) |
| 67 | + return 0; |
| 68 | + |
| 69 | + for (int[] pool : list) { |
| 70 | + water += height - map[pool[0]][pool[1]]; |
| 71 | + map[pool[0]][pool[1]] = height; |
| 72 | + } |
| 73 | + return water; |
| 74 | + } |
| 75 | +} |
| 76 | +``` |
0 commit comments