Skip to content

Commit 76c275f

Browse files
committed
[BFS] baekjoon-7576
1 parent c7e9ba9 commit 76c275f

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

src/BFS/P7576/Main2.java

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package BFS.P7576;
2+
3+
import java.io.*;
4+
import java.util.*;
5+
6+
public class Main2 {
7+
8+
static int M, N, zero, cnt;
9+
static int[][] map;
10+
static int[] di = {-1, 0, 1, 0}, dj = {0, 1, 0, -1};
11+
static Queue<Pos> q = new LinkedList<>();
12+
13+
public static void main(String[] args) throws Exception {
14+
System.setIn(new FileInputStream("src/BFS/P7576/input.txt"));
15+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
16+
StringTokenizer st = new StringTokenizer(br.readLine());
17+
18+
M = Integer.parseInt(st.nextToken());
19+
N = Integer.parseInt(st.nextToken());
20+
map = new int[N][M];
21+
for (int i = 0; i < N; i++) {
22+
st = new StringTokenizer(br.readLine());
23+
for (int j = 0; j < M; j++) {
24+
map[i][j] = Integer.parseInt(st.nextToken());
25+
if (map[i][j] == 1) q.offer(new Pos(i, j, 0));
26+
else if (map[i][j] == 0) zero ++;
27+
}
28+
}
29+
30+
while (!q.isEmpty()) {
31+
Pos p = q.poll();
32+
for (int k = 0; k < 4; k++) {
33+
int to_i = p.i + di[k];
34+
int to_j = p.j + dj[k];
35+
if (isValidPath(to_i, to_j) && map[to_i][to_j] == 0) {
36+
map[to_i][to_j] = 1;
37+
q.offer(new Pos(to_i, to_j, p.d+1));
38+
zero --;
39+
}
40+
}
41+
cnt = p.d;
42+
}
43+
44+
if (zero > 0) System.out.println(-1);
45+
else System.out.println(cnt);
46+
}
47+
48+
static boolean isValidPath(int i, int j) {
49+
return 0 <= i && i < N && 0 <= j && j < M;
50+
}
51+
52+
static class Pos {
53+
int i, j, d;
54+
55+
public Pos(int i, int j, int d) {
56+
this.i = i;
57+
this.j = j;
58+
this.d = d;
59+
}
60+
}
61+
}

src/BFS/P7576/README.md

+6
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,9 @@
22

33
![image](https://user-images.githubusercontent.com/22045163/96839353-052ce900-1484-11eb-845f-d76c0d11a9a3.png)
44

5+
![image](https://user-images.githubusercontent.com/22045163/114639163-21f5fb00-9d08-11eb-8a09-a236fd327ad9.png)
6+
7+
### 2021.04.14
8+
9+
- [210414.java](Main2.java)
10+
![image](https://user-images.githubusercontent.com/22045163/114639207-30441700-9d08-11eb-8c48-3f8ea4595757.png)

0 commit comments

Comments
 (0)