알고리즘/백준 풀이(탐색)
백준 1303번 - 전쟁 - 전투(DFS)
공부 기록장
2024. 4. 24. 19:49
▶코드
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++;
}
}
}
}