[BOJ 1303] ์ ์-์ ํฌ
1. ๋ฌธ์ : Link
๊ทธ๋ํ ํ์ํ๋ฉด์ ์๊ตฐ ์ ๊ตฐ ํ ๋น๊ต
2. ํ์ด
DFS ํ์ด
* ์ธ๋ฑ์ค ์ ๊ทผํ ๋ ํญ์ ์ฃผ์ํ๊ธฐ!
(๊ฐ๋ก ์ธ๋ก ํท๊ฐ๋ฆฌ๊ธฐ ์ฌ์)
3. ์ฝ๋
package baekjoon;
import java.io.IOException;
import java.util.*;
public class ์ ์์ ํฌ {
static int N,M;
static char[][] map;
static boolean[][] visited;
static int[] xx = {0,0,1,-1};
static int[] yy = {1,-1,0,0};
static int wVal = 0;
static int bVal = 0;
static int cnt = 0;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
map = new char[M][N];
visited = new boolean[M][N];
for(int i=0; i<M; i++){
String temp = sc.next();
for(int j=0; j<N; j++){
map[i][j] = temp.charAt(j);
}
}
for(int i=0; i<M; i++){
for(int j=0; j<N; j++){
if(!visited[i][j] && map[i][j] == 'W'){
dfs(i,j,'W');
wVal += cnt*cnt;
}else if(!visited[i][j] && map[i][j] == 'B'){
dfs(i,j,'B');
bVal += cnt*cnt;
}
cnt = 0;
}
}
System.out.print(wVal + " " + bVal);
}
public static void dfs(int x, int y, char color) {
visited[x][y] = true;
cnt++;
for(int i=0; i<4; i++){
int ix = x + xx[i];
int iy = y + yy[i];
if(ix >= 0 && ix < M && iy >= 0 && iy<N && !visited[ix][iy] && map[ix][iy] == color){
dfs(ix,iy,color);
}
}
}
}
'๐ป Coding Problems Solving > DFS | BFS | Backtracking' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค] LV.2 ํ๋ ์ฆ4๋ธ๋ก (0) | 2023.03.13 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค] LV.2 ํผ๋ก๋ (์๋ฐ java) (0) | 2023.03.01 |
[BOJ 1260] DFS์ BFS (0) | 2022.07.01 |
[BOJ 17070] ํ์ดํ ์ฎ๊ธฐ๊ธฐ1 (java) (0) | 2022.07.01 |
[BOJ 2667] ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ (0) | 2022.06.29 |
์ต๊ทผ๋๊ธ