Algorithm
[BOJ_7576] ํ ๋งํ (๊ณจ๋ 5) - JAVA
์ด์๋ฐ
2023. 10. 11. 16:59
๐พ ์๊ณ ๋ฆฌ์ฆ
- BFS (๋๋น ์ฐ์ ํ์) ์ ํ์ฉํ ์ฌ๊ท ์๊ณ ๋ฆฌ์ฆ
- ๋ธํ๋ฅผ ์ด์ฉํ 4๋ฐฉ ํ์
๐พ ์๊ฐ ํฌ์ธํธ
- ์ฒ์์๋ r,c,day๋ฅผ ๋ด๋ ํด๋์ค๋ฅผ ๋ง๋ค์ง ์๊ณ , ๋ฐฐ์ด์ ๋ด๋ ํ๋ก ์์ฑํ์๋๋ฐ, ํ ๋งํ ๊ฐ ๋ณต์๊ฐ์ผ ๋ ๋์์ ์ต๋๋ค๋ ๊ฒ์ ๊ฐ๊ณผํ์ฌ์ ๋ฌธ์ ๊ฐ ์ ํ๋ฆฌ์ง ์์๋ค. (๋์์ ์ต๋๋ค๋ ๊ฒ์ ์ฝ๋๋ก ๋ํ๋ด๋ฉด, box์ ๊ฐ์ด 1์ผ ๋ queue.addํด์ฃผ๋ฉด ๋๋ค. 1์ธ(์ต์ ํ ๋งํ ) ์ขํ๋ค์ ํ์ ๋ด์์ฃผ๊ณ bfs ๋ฉ์๋๋ฅผ ํธ์ถํด์ผ ํ๋ ๊ฒ์ด๋ค.
- ๋๋ฒ์งธ ์๋๋ก, r, c, day๋ฅผ ๋ด๋ ํด๋์ค๋ฅผ ๋ง๋ค์๊ณ , ๊ทธ ๋, ๊ฐ์ด 1์ธ ์ขํ๋ค์ ์ ์ฅํด์ฃผ๊ธฐ ์ํด ArrayList๋ฅผ ์์ฑํด์ฃผ์๋ค. (isOneList) → new tomato ์ฃผ์ !!
- day๋ฅผ ์ ์ฅํด์ค ๋ณ์(์๋ day) ์์ฑํ์ฌ day๋ฅผ ๋ง์ง๋ง์ ์ถ๋ ฅํ ์ ์๋๋ก ํ ๊ฒ.
- check ๋ฉ์๋๋ฅผ ํตํด ๋ง์ง๋ง ๋ ์ ์์ต์ ํ ๋งํ (0) ์ด ์๋์ง ์๋์ง ํ์ธํ๋ค.
๐พ ์์ค์ฝ๋
package boj;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
class Tomato {
int r;
int c;
int day;
public Tomato(int r, int c, int day) {
super();
this.r = r;
this.c = c;
this.day = day;
}
}
public class Main {
static int M;
static int N;
static int[][] box;
static Queue<Tomato> queue = new LinkedList<>();
static ArrayList<Tomato> isOneList;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
M = Integer.parseInt(st.nextToken()); // ๊ฐ๋ก
N = Integer.parseInt(st.nextToken()); // ์ธ๋ก
box = new int[N][M];
isOneList = new ArrayList<>();
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < M; j++) {
box[i][j] = Integer.parseInt(st.nextToken());
if (box[i][j] == 1) {
isOneList.add(new Tomato(i, j, 0)); //๊ฐ์ด 1์ธ ์ ๋ค์ ๋ด์์ค ๋ฆฌ์คํธ
}
}
} // ์
๋ ฅ๋
bfs(M, N);
}
private static void bfs(int r, int c) {
queue = new LinkedList<>();
for (int i = 0; i < isOneList.size(); i++) {
queue.add(isOneList.get(i));
}
int[] dr = { -1, 1, 0, 0 };
int[] dc = { 0, 0, -1, 1 };
int day = 0;
while (!queue.isEmpty()) {
Tomato t = queue.poll();
day = t.day;
for (int d = 0; d < 4; d++) {
int nr = t.r + dr[d];
int nc = t.c + dc[d];
if (nr >= 0 && nc >= 0 && nr < N && nc < M) {
if (box[nr][nc] == 0) {
box[nr][nc] = 1;
queue.add(new Tomato(nr, nc, day + 1));
}
}
}
}
if (check()) {
System.out.println(day);
} else {
System.out.println(-1);
}
}
private static boolean check() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (box[i][j] == 0)
return false;
}
}
return true;
}
}
๐ต๐ซ ๊ณต๋ถํด์ผ ํ ์
- class ๋ง๋๋ ์ฐ์ต
- ๊ทธ class ์ ๋ด์ ๋ณ์๋ฅผ ์ ํ์ฉํ ์ ์๋๋ก ์ฐ์ต
- cnt ํ๊ธฐ ์ด๋ ค์ธ ๋๋ ๋ฉ์๋์ ์ธ์๋ก ๊ฐ์ด ๋ด์์ฃผ์.