92 lines
3.2 KiB
Java
92 lines
3.2 KiB
Java
import java.util.*;
|
|
|
|
public class _10026 {
|
|
|
|
public static int countAreaBFS(String[] grid, int N){
|
|
int[] dx = {1,-1,0,0};
|
|
int[] dy = {0,0,1,-1};
|
|
Deque<Integer> qx = new ArrayDeque<>();
|
|
Deque<Integer> qy = new ArrayDeque<>();
|
|
boolean[][] visited = new boolean[N][N];
|
|
int countArea = 0;
|
|
|
|
for(int i=0; i<N; i++){
|
|
for(int j=0; j<N; j++){
|
|
if(!visited[i][j]){
|
|
visited[i][j] = true;
|
|
char color = grid[i].charAt(j);
|
|
qx.add(j);
|
|
qy.add(i);
|
|
while(qx.size() != 0 && qy.size() != 0){
|
|
int cx = qx.poll();
|
|
int cy = qy.poll();
|
|
for(int d=0; d<4; d++){
|
|
int nx = cx + dx[d];
|
|
int ny = cy + dy[d];
|
|
if(0<=nx && nx<N && 0<=ny && ny<N && grid[ny].charAt(nx) == color && !visited[ny][nx]){
|
|
visited[ny][nx] = true;
|
|
qx.add(nx);
|
|
qy.add(ny);
|
|
}
|
|
}
|
|
}
|
|
countArea += 1;
|
|
}
|
|
}
|
|
}
|
|
return countArea;
|
|
}
|
|
|
|
public static int countAreaDFS(String[] grid, int N){
|
|
int[] dx = {1,-1,0,0};
|
|
int[] dy = {0,0,1,-1};
|
|
boolean[][] visited = new boolean[N][N];
|
|
Stack<Integer> sx = new Stack<>();
|
|
Stack<Integer> sy = new Stack<>();
|
|
int countArea = 0;
|
|
|
|
for(int x=0; x<N; x++){
|
|
for(int y=0; y<N; y++){
|
|
if(!visited[y][x]){
|
|
visited[y][x] = true;
|
|
char color = grid[y].charAt(x);
|
|
sx.push(x);
|
|
sy.push(y);
|
|
while(sx.size() != 0 && sy.size() != 0){
|
|
int cx = sx.pop();
|
|
int cy = sy.pop();
|
|
|
|
for(int d=0; d<4; d++){
|
|
int nx = cx + dx[d];
|
|
int ny = cy + dy[d];
|
|
if(0<=nx && nx<N && 0<=ny && ny<N && grid[ny].charAt(nx) == color && !visited[ny][nx]){
|
|
sx.add(nx);
|
|
sy.add(ny);
|
|
visited[ny][nx] = true;
|
|
}
|
|
}
|
|
}
|
|
countArea += 1;
|
|
}
|
|
}
|
|
}
|
|
return countArea;
|
|
}
|
|
public static void main(String[] args) {
|
|
Scanner sc = new Scanner(System.in);
|
|
int N = Integer.parseInt(sc.nextLine());
|
|
String[] grid_normal = new String[N];
|
|
String[] grid_blindness = new String[N];
|
|
for(int i=0; i<N; i++){
|
|
String line = sc.nextLine();
|
|
grid_normal[i] = line;
|
|
grid_blindness[i] = line.replace('R', 'G');
|
|
}
|
|
sc.close();
|
|
|
|
int areaCount_normal = countAreaBFS(grid_normal, N);
|
|
int areaCount_blindness = countAreaDFS(grid_blindness, N);
|
|
|
|
System.out.println(areaCount_normal + " " + areaCount_blindness);
|
|
}
|
|
} |