https://sihyungyou.github.io/boj-2636/
백준 2636번 : 치즈
BOJ
sihyungyou.github.io
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int[][] che;
static int N;
static int M;
static int[] x_move = {-1,1,0,0};
static int[] y_move = {0,0,-1,1};
static int cheese = 0;
public static void main(String arg[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
che = new int[N][M];
int time = 0;
for(int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine(), " ");
for(int j = 0; j < M; j++) {
che[i][j] = Integer.parseInt(st.nextToken());
if(che[i][j] == 1)
cheese++;
}
}
int result = 0;
while(cheese != 0) {
time++;
result = cheese;
bfs();
}
System.out.println(time);
System.out.println(result);
}
static void bfs() {
//빈 공간(공기가 통하는 연결된 곳)을 큐에 넣는다
Queue<int[]> q = new LinkedList<>();
int dis = 3;
q.add(new int[] {0,0});
boolean [][]visit = new boolean[N][M]; //공기가 닿은 치즈를 0으로 바꿀 때 방문처리를 해 이번 수행에서 빈 공간으로 포함되지 않게함
while(!q.isEmpty()) {
int[] cur = q.poll();
int x = cur[0];
int y = cur[1];
for(int i = 0; i < 4; i++) {
int tx = x+x_move[dis];
int ty = y+y_move[dis];
if(tx >= 0 && tx < N && ty >= 0 && ty < M && !visit[tx][ty]) {
if(che[tx][ty] == 0) {
q.add(new int[] {tx,ty});
visit[tx][ty] = true;
}
else { //1 치즈인 곳이라면
che[tx][ty] = 0; //치즈가 녹음
visit[tx][ty] = true;
cheese--;
}
}
dis = change(dis);
}
}
}
static int change(int n) {
if(n == 0)
return 3;
else
return n-1;
}
}
'백준' 카테고리의 다른 글
[백준] 2156 포도주 시식[자바] (0) | 2021.12.23 |
---|---|
[백준] 1912 연속합 [자바] (0) | 2021.12.21 |
[백준] 9466 텀 프로젝트 [자바] (0) | 2021.12.08 |
[백준] 2206 벽 부수고 이동하기 [자바] (0) | 2021.12.07 |
[백준] 7576 토마토 [자바] (0) | 2021.12.07 |