▶코드
import java.util.*;
import java.io.*;
public class Main {
static int N, M, cnt, e_result, t_result;
static char arr[][];
static boolean visited[][];
static int dx[] = {0, 0, -1, 1};
static int dy[] = {-1, 1, 0, 0};
static LinkedList<Integer> team;
static LinkedList<Integer> enemy;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
arr = new char[M][N];
visited = new boolean[M][N];
team = new LinkedList<>();
enemy = new LinkedList<>();
cnt = 1;
for (int i = 0; i < M; i++) {
String str = br.readLine();
for (int j = 0; j < N; j++) {
arr[i][j] = str.charAt(j);
}
}
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (!visited[i][j]) {
dfs(i,j);
if(arr[i][j]=='W'){
team.add(cnt);
} else if(arr[i][j]=='B'){
enemy.add(cnt);
}
cnt = 1;
}
}
}
for(int i=0;i<team.size();i++){
t_result += Math.pow(team.get(i),2);
}
for(int i=0;i<enemy.size();i++){
e_result += Math.pow(enemy.get(i),2);
}
System.out.println(t_result + " " + e_result);
}
public static void dfs(int x, int y) {
visited[x][y] = true;
for (int i = 0; i < 4; i++) {
int nx = dx[i] + x;
int ny = dy[i] + y;
if (nx >= 0 && ny >= 0 && nx < M && ny < N && !visited[nx][ny] && arr[x][y] == arr[nx][ny]){
dfs(nx,ny);
cnt++;
}
}
}
}
'알고리즘 > 백준 풀이(탐색)' 카테고리의 다른 글
백준 3184번 - 양(DFS) (0) | 2024.05.07 |
---|---|
백준 14716번 - 현수막 (0) | 2024.04.30 |
백준 1743번 - 음식물 피하기 (0) | 2024.04.23 |
백준 2583번 - 영역 구하기(DFS) (0) | 2024.04.21 |
백준 4963번 - 섬의 개수(DFS) (1) | 2024.04.20 |