BFS ํจ์๋ฅผ ์๋ฐ๋ก ์ฒ์ ์์ฑํด๋ดค๋ค.
์ฃผ์ ํค์๋๋ ๋ค์๊ณผ ๊ฐ๋ค!
Queue<int[]> queue = new LinkedList<>(); // LinkedList๋ก ๊ตฌํ
q.offer(new int[] {0,0}); // q์ ์์ ๋ฃ๊ธฐ, ํ ์ฐจ์์ ๋ false ๋ฐํ
q.poll(); // q์์ ์์ ๋นผ๊ธฐ
q.add(new int[] {nx, ny}); // q์ ์์ ๋ฃ๊ธฐ, ํ ์ฐจ์์ ๋ ์๋ฌ ๋ฐํ
&& ๋ฅผ ์ฌ์ฉํด์ ์กฐ๊ฑด๋ฌธ์ ๋ค ๋ถ๋ฆฌ์์ผ ์์ฑํด์ผํจ์ฒ์์๋ ์ด๋ป๊ฒ ์น์ฆ์ ํ ๋๋ฆฌ๋ง์ ํ์ ํ์ง? ๋ผ๋ ์๊ฐ์ ํ๋ค.
์น์ฆ๊ฐ ์ค์ฌ์ด ์๋๋ผ ๊ณต๊ธฐ๋ฅผ ์ค์ฌ์ผ๋ก ํ์์ ํด์ผํ๋ค!
๊ณต๊ธฐ๋ถํฐ ์์ํด์ ํ์ํ๋ค๊ฐ **1์ด ๋์ค๋ฉด 0์ผ๋ก ๋ณํ์ํค๊ณ , visited = True๋ก ๋ณ๊ฒฝ**ํ๋ค. 2๋ก ๋ณํํ๊ธฐ๋ ํ๋๋ฐ, ๊ตณ์ด ๊ทธ๋ดํ์๊ฐ ์์๋ค.
์ด๋ฏธ ๋ฐฉ๋ฌธํ์ผ๋ฏ๋ก 0์ผ๋ก ๋ฐ๊ฟ๋ ๊ทธ ๋ ธ๋๊ฐ ํ์ ๋ค์ด๊ฐ์ผ์ด ์์ผ๋ฏ๋ก ํ ๋๋ฆฌ๋ง 0์ผ๋ก ๋ณ๊ฒฝ๋๋ค.
์ด 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 G2636 {
static int n, m;
static int cheese;
static int[][] graph;
static boolean[][] visited;
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};
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());
// ์ ์ฒด ์น์ฆ์ ๊ฐ์๋ฅผ ๊ตฌํ๋ค.
graph = new int[n][m];
for(int i=0; i<n; i++) {
st = new StringTokenizer(br.readLine());
for(int j=0; j<m; j++) {
graph[i][j] = Integer.parseInt(st.nextToken());
// ์ ์ฒด ์น์ฆ์ ๊ฐ์๋ฅผ ๊ตฌํ๋ค.
if (graph[i][j] == 1) cheese++;
}
}
int cheeseCnt = 0;
int time = 0;
while (cheese != 0) {
cheeseCnt = cheese;
time ++;
visited = new boolean[n][m];
bfs();
}
System.out.println(time);
System.out.println(cheeseCnt);
}
public static void bfs() {
Queue<int[]> q = new LinkedList<>();
// ํ ๊ฐ์ฅ์๋ฆฌ์๋ ์น์ฆ๊ฐ ๋์ฌ์์ง์๋ค๊ณ ํ์ผ๋ฏ๋ก (0,0) ๋ถํฐ ์์
q.offer(new int[] {0, 0});
visited[0][0] = true;
while(!q.isEmpty()) {
int[] current = q.poll();
for (int i =0; i < 4; i++) {
int nx = current[0] + dx[i];
int ny = current[1] + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && !visited[nx][ny]) {
visited[nx][ny] = true;
if (graph[nx][ny] == 0) {
// add : ํ๊ฐ ๊ฝ ์ฐฌ ๊ฒฝ์ฐ ์์ธ ๋ฐ์ ์ํด
// offer : ์ถ๊ฐ ์คํจ๋ฅผ ์๋ฏธํ๋ false ๋ฆฌํด
q.add(new int[] {nx, ny});
} else {
cheese --;
// ์ด๋ฏธ ๋ฐฉ๋ฌธํ์ผ๋ฏ๋ก ์น์ฆ๋ฅผ 0์ผ๋ก ๋ฐ๊ฟ๋ ํ์ํ์ง ์๋๋ค.
graph[nx][ny] = 0;
}
}
}
}
}
}