첫째 줄에는 사각형 모양 판의 세로와 가로의 길이가 양의 정수로 주어진다.
세로와 가로의 길이는 최대 100이다. 판의 각 가로줄의 모양이 윗 줄부터 차례로 둘째 줄부터 마지막 줄까지 주어진다.
치즈가 없는 칸은 0, 치즈가 있는 칸은 1로 주어지며 각 숫자 사이에는 빈칸이 하나씩 있다.
첫째 줄에는 치즈가 모두 녹아서 없어지는 데 걸리는 시간을 출력하고, 둘째 줄에는 모두 녹기 한 시간 전에 남아있는 치즈조각이 놓여 있는 칸의 개수를 출력한다.
입력받는 과정에서 전체 치즈의 갯수를 저장하고
치즈의 갯수가 0이 될 때까지 bfs
를 반복
공기와 접한다면 큐에 삽입하고
치즈를 만난다면 0으로 변경하고 치즈의 갯수를 줄인다.
while (cheese != 0) {
time++;
cnt = cheese;
bfs();
}
이 부분만 조심해주면 되는 문제였던거같다!
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 N, M , cnt, cheese, time;
static int[][] maps;
static boolean[][] visited;
static int[] dx = {0, 0, -1, 1};
static int[] dy = {1, -1, 0, 0};
public static void main(String[] args) 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());
maps = new int[N][M];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < M; j++) {
maps[i][j] = Integer.parseInt(st.nextToken());
if(maps[i][j] == 1) cheese++;
}
}
while (cheese != 0) {
time++;
cnt = cheese;
dfs();
}
System.out.println(time);
System.out.println(cnt);
}
public static void bfs() {
visited = new boolean[N][M];
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{0, 0});
visited[0][0] = true;
while (!queue.isEmpty()) {
int[] cur = queue.poll();
for (int i = 0; i < 4; i++) {
int nx = cur[0] + dx[i];
int ny = cur[1] + dy[i];
if(nx<0 || nx>=N || ny<0 || ny>=M) continue;
if (visited[nx][ny]) continue;
if (maps[nx][ny] == 1) {
cheese--;
maps[nx][ny] = 0;
} else if (maps[nx][ny] == 0) {
queue.offer(new int[]{nx, ny});
}
visited[nx][ny] = true;
}
}
}
}