|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static char[][] map; |
| 7 | + static boolean[][] visited; |
| 8 | + |
| 9 | + static int[] dy = {-1, 1, 0, 0}; |
| 10 | + static int[] dx = {0, 0, -1, 1}; |
| 11 | + |
| 12 | + public static void main(String[] args) throws IOException { |
| 13 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 14 | + int n = Integer.parseInt(br.readLine()); |
| 15 | + map = new char[n][n]; |
| 16 | + visited = new boolean[n][n]; |
| 17 | + |
| 18 | + for (int i=0; i<n; i++){ |
| 19 | + String st = br.readLine(); |
| 20 | + for (int j=0; j<n; j++){ |
| 21 | + map[i][j] = st.charAt(j); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + int count = 0; |
| 26 | + int rgcount = 0; |
| 27 | + |
| 28 | + for (int i=0; i<n; i++){ |
| 29 | + for (int j=0; j<n; j++){ |
| 30 | + if (!visited[i][j]){ |
| 31 | + Queue<int[]> queue = new ArrayDeque<>(); |
| 32 | + queue.add(new int[]{i, j}); |
| 33 | + visited[i][j] = true; |
| 34 | + |
| 35 | + while (!queue.isEmpty()){ |
| 36 | + int[] cur = queue.poll(); |
| 37 | + |
| 38 | + for (int k=0; k<4; k++){ |
| 39 | + int nx = cur[0] + dx[k]; |
| 40 | + int ny = cur[1] + dy[k]; |
| 41 | + |
| 42 | + if (nx < n && nx >= 0 && ny < n && ny >= 0 && !visited[nx][ny] |
| 43 | + && map[cur[0]][cur[1]] == map[nx][ny]){ |
| 44 | + visited[nx][ny] = true; |
| 45 | + queue.add(new int[]{nx, ny}); |
| 46 | + |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + count++; |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + for (int i=0; i<n; i++){ |
| 56 | + Arrays.fill(visited[i], false); |
| 57 | + } |
| 58 | + |
| 59 | + for (int i=0; i<n; i++){ |
| 60 | + for (int j=0; j<n; j++){ |
| 61 | + if (!visited[i][j]){ |
| 62 | + Queue<int[]> queue = new ArrayDeque<>(); |
| 63 | + queue.add(new int[]{i, j}); |
| 64 | + visited[i][j] = true; |
| 65 | + |
| 66 | + while (!queue.isEmpty()){ |
| 67 | + int[] cur = queue.poll(); |
| 68 | + |
| 69 | + for (int k=0; k<4; k++){ |
| 70 | + int nx = cur[0] + dx[k]; |
| 71 | + int ny = cur[1] + dy[k]; |
| 72 | + |
| 73 | + if (nx < n && nx >= 0 && ny < n && ny >= 0 && !visited[nx][ny] |
| 74 | + && ((map[cur[0]][cur[1]] == 'B' && map[nx][ny] == 'B') || (map[cur[0]][cur[1]] != 'B' && map[nx][ny] != 'B'))){ |
| 75 | + visited[nx][ny] = true; |
| 76 | + queue.add(new int[]{nx, ny}); |
| 77 | + |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + rgcount++; |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + System.out.println(count + " " + rgcount); |
| 87 | + } |
| 88 | +} |
| 89 | +``` |
0 commit comments