๋ฐ์ํ
๋ฌธ์ (Silver 2)
https://www.acmicpc.net/problem/3184
ํ์ด
1. ์ ๋๋ ๋๋๊ฐ ์๋ ์์ญ์ ๊ฒ์ฌ (BFS)
2. ๊ทธ๋ํ๋ฅผ ๋๋ฉฐ ์๊ณผ ๋๋์ ์์น ์ ์ฅ
3. ํ์ ํ, ์๊ณผ ๋๋ ๋ฆฌ์คํธ ํฌ๊ธฐ ๋น๊ต ํ map์ ๋ฐ์
์ฝ๋
๋๋ณด๊ธฐ
import java.util.*;
import java.io.*;
public class Main {
static int[] di = {-1,0,1,0};
static int[] dj = {0,-1,0,1};
static int R,C;
static char[][] map;
static boolean[][] visited ;
static List<int[]> sheep, inSheep;
static List<int[]> wolf, inWolf;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
R = Integer.parseInt(st.nextToken());
C = Integer.parseInt(st.nextToken());
map = new char[R][C];
visited = new boolean[R][C];
sheep = new ArrayList<>(); // ์์ญ ๋ด ์์ ์์น ์ ์ฅ
wolf = new ArrayList<>(); // ์์ญ ๋ด ๋๋ ์์น ์ ์ฅ
for(int i =0 ; i < R ; i++){
String str = br.readLine();
for(int j =0 ; j < C ; j++){
map[i][j] = str.charAt(j);
}
}
for(int i =0 ; i < R ; i++){
for(int j = 0 ; j < C ; j++){
if(map[i][j] == 'v' || map[i][j] == 'o'){ // ๋๋์ ์์ ๋ง๋๋ค๋ฉด
wolf = new ArrayList<>();
sheep = new ArrayList<>();
attack(i, j); // ์์ญ ๊ฒ์ฌ
if(wolf.size() < sheep.size()){ // ์์ ์๊ฐ ๋ ๋ง์ ๋
for(int[] w : wolf){
map[w[0]][w[1]] = '.'; // ๋๋ ์์น ๊ฐ ๋ณ๊ฒฝ
}
}else{
for(int[] s : sheep){ // ๋๋ ์๊ฐ ๋ ๋ง์ ๋
map[s[0]][s[1]] = '.'; // ์์ ์์น ๊ฐ ๋ณ๊ฒฝ
}
}
}
}
}
int wolfCnt = 0;
int sheepCnt = 0;
for(int i =0 ; i < R ; i++){
for(int j =0 ; j < C ;j++){
if(map[i][j] == 'v') wolfCnt ++;
else if(map[i][j] == 'o') sheepCnt++;
}
}
System.out.println(sheepCnt+" "+wolfCnt);
}
/* ์์ญ ๊ฒ์ฌ๋ฅผ ์ํ BFS */
private static void attack(int i, int j) {
Queue<int[]> q = new ArrayDeque<>();
q.offer(new int[]{i, j});
visited[i][j] = true;
while(!q.isEmpty()){
int[] cur = q.poll();
if(map[cur[0]][cur[1]] == 'v'){
wolf.add(new int[]{cur[0], cur[1]});
}
else if(map[cur[0]][cur[1]] == 'o') {
sheep.add(new int[]{cur[0], cur[1]});
}
for(int d = 0 ; d < 4 ; d++){
int ni = cur[0] + di[d];
int nj = cur[1] + dj[d];
if(0<=ni&&ni<R && 0<=nj&&nj<C){
if(!visited[ni][nj] && map[ni][nj] != '#'){
q.offer(new int[]{ni, nj});
visited[ni][nj] = true;
}
}
}
}
}
}
๋ฐ์ํ
'๐ ์๊ณ ๋ฆฌ์ฆ > GraphTraversal' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 11967๋ฒ: ๋ถ์ผ๊ธฐ (JAVA) (0) | 2022.04.04 |
---|---|
[๋ฐฑ์ค] 14466๋ฒ: ์๊ฐ ๊ธธ์ ๊ฑด๋๊ฐ ์ด์ 6 (JAVA) (0) | 2022.03.28 |
[๋ฐฑ์ค] 5427๋ฒ ๋ถ (Java) (0) | 2022.02.08 |
[๋ฐฑ์ค] 2606๋ฒ ๋ฐ์ด๋ฌ์ค (Java) (0) | 2021.08.24 |
[๋ฐฑ์ค] 2667๋ฒ ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ (Java) (0) | 2021.08.24 |