|
| 1 | +```java |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStreamReader; |
| 5 | +import java.util.ArrayDeque; |
| 6 | + |
| 7 | +public class Main { |
| 8 | + private static final int[] dr = {-1, 0, 1, 0}; |
| 9 | + private static final int[] dc = {0, 1, 0, -1}; |
| 10 | + |
| 11 | + public static void main(String[] args) throws IOException { |
| 12 | + var br = new BufferedReader(new InputStreamReader(System.in)); |
| 13 | + int n = Integer.parseInt(br.readLine()); |
| 14 | + char[][] normal = new char[n][n]; |
| 15 | + char[][] weak = new char[n][n]; |
| 16 | + for (int i = 0; i < n; i++) { |
| 17 | + String line = br.readLine(); |
| 18 | + for (int j = 0; j < n; j++) { |
| 19 | + char c = line.charAt(j); |
| 20 | + normal[i][j] = c; |
| 21 | + weak[i][j] = (c == 'G') ? 'R' : c; |
| 22 | + } |
| 23 | + } |
| 24 | + int normalCount = countAreas(normal, n); |
| 25 | + int weakCount = countAreas(weak, n); |
| 26 | + |
| 27 | + System.out.printf("%d %d\n", normalCount, weakCount); |
| 28 | + } |
| 29 | + private static int countAreas(char[][] map, int n) { |
| 30 | + boolean[][] visited = new boolean[n][n]; |
| 31 | + int count = 0; |
| 32 | + var queue = new ArrayDeque<int[]>(); |
| 33 | + |
| 34 | + for (int r = 0; r < n; r++) { |
| 35 | + for (int c = 0; c < n; c++) { |
| 36 | + if (visited[r][c]) |
| 37 | + continue; |
| 38 | + char color = map[r][c]; |
| 39 | + count++; |
| 40 | + visited[r][c] = true; |
| 41 | + queue.offer(new int[] {r, c}); |
| 42 | + while (!queue.isEmpty()) { |
| 43 | + int[] now = queue.poll(); |
| 44 | + for (int d = 0; d < 4; d++) { |
| 45 | + int nr = now[0] + dr[d]; |
| 46 | + int nc = now[1] + dc[d]; |
| 47 | + if (nr >= 0 && nr < n && nc >= 0 && nc < n |
| 48 | + && !visited[nr][nc] |
| 49 | + && map[nr][nc] == color) { |
| 50 | + visited[nr][nc] = true; |
| 51 | + queue.offer(new int[] {nr, nc}); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + return count; |
| 58 | + } |
| 59 | +} |
| 60 | +``` |
0 commit comments