Algorithm/BOJ
[Silver I/JAVA] 3187 μμΉκΈ° κΏ
carsumin
2024. 12. 19. 11:10
https://www.acmicpc.net/problem/3187
쑰건
- μ > λλ -> μλ§ λ¨μ , λλ >= μ -> λλλ§ λ¨μ
- μΈν리 λ°κΉ₯μλ μ λλ μμ
- λΉκ³΅κ° μμ
νμν κ²
- λ°©λ¬Έ μ¬λΆ 체ν¬
- λ°©ν₯ μ΄λ λ°°μ΄ dx, dy
- μΈν리, λΉκ³΅κ°, μλλ μ λ ₯ λ°μ map λ°°μ΄
- μ λ ₯μ 곡백μμ΄ λ°μ (charAt μ¬μ©)
νμ΄ κ³Όμ
- λ°©λ¬Έν μ μκ³ , μΈνλ¦¬κ° μλλ©΄ BFS νμ
- μνμ’μ° λ°©ν₯ μ΄λνλ©΄μ BFS νμμ νκ³ λλμ μμ κ°μλ₯Ό κ°κ° μΉ΄μ΄νΈ
- λ§μ§λ§μ μ΅μ’ λλμ μμ κ°μλ₯Ό λΉκ΅
- μ’ν ννλ‘ νμ νλ²μ λ΄μ μ μμ
μ 체 μ½λ
import java.io.*;
import java.util.*;
public class Main{
static int R,C; //κ°λ‘C,μΈλ‘R
static char[][] map;
static boolean[][] visited;
static int[] dx = {-1,1,0,0};
static int[] dy = {0,0,-1,1};
static int wolf = 0;
static int sheep = 0;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
R = Integer.parseInt(str[0]); //μΈλ‘
C = Integer.parseInt(str[1]); //κ°λ‘
map = new char[R][C];
visited = new boolean[R][C];
//mapμ΄κΈ°ν
for(int i=0; i<R; i++){
String s = br.readLine();
for(int j=0; j<C; j++){
map[i][j] = s.charAt(j);
}
}
for(int i=0; i<R; i++){
for(int j=0; j<C; j++){
//λ°©λ¬Έx μΈν리x
if(!visited[i][j] && map[i][j] != '#'){
bfs(i,j);
}
}
}
//κ²°κ³Ό μΆλ ₯
System.out.println(sheep + " " + wolf);
}
private static void bfs(int x, int y){
//μ’νννλ‘ μ μ₯νκΈ° μν ν μ μΈ
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{x,y}); //ν¬κΈ°κ° 2μΈ μ μλ°°μ΄ κ° μΆκ°
visited[x][y] = true;
int sheepCnt = 0;
int wolfCnt = 0;
if(map[x][y] == 'k') sheepCnt++;
if(map[x][y] == 'v') wolfCnt++;
while(!queue.isEmpty()){ //νμ κ°μ΄ μμΌλ©΄ λ°λ³΅
int[] current = queue.poll(); //νμ¬κ° κΊΌλ
int currentX = current[0];
int currentY = current[1];
for(int i=0; i<4; i++){
int nx = currentX + dx[i];
int ny = currentY + dy[i];
if(nx >= 0 && nx < R && ny >= 0 && ny < C && !visited[nx][ny] && map[nx][ny] != '#'){
visited[nx][ny] = true;
queue.offer(new int[]{nx, ny});
//μ, λλ μΉ΄μ΄νΈ
if(map[nx][ny] == 'k') sheepCnt++;
if(map[nx][ny] == 'v') wolfCnt++;
}
}
}
if(sheepCnt > wolfCnt){ //μ>λλ -> μ κ°μλ§ λ¨μ
sheep += sheepCnt;
}else{
wolf += wolfCnt;
}
}
}