728x90
반응형
https://www.acmicpc.net/problem/7576
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
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 class Node {
int x;
int y;
int z;
Node (int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
}
static int max = 0;
static int count = 0;
static int N, M;
static int[][] map;
static boolean[][] visited;
static Queue<Node> q = new LinkedList<>();
static int[] dxy = {1, 0, -1, 0, 1};
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());
map = new int[N][M];
visited = new boolean[N][M];
count = N * M;
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < M; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
if (map[i][j] == 1) {
q.offer(new Node(i, j, 0));
visited[i][j] = true;
}
if (map[i][j] == 1 || map[i][j] == -1) {
count--;
}
}
}
bfs();
if (count == 0) {
System.out.println(max);
return;
}
System.out.println(-1);
}
static void bfs() {
while (!q.isEmpty()) {
Node cur = q.poll();
max = Math.max(max, cur.z);
for (int i = 0; i < 4; i++) {
int nx = cur.x + dxy[i];
int ny = cur.y + dxy[i + 1];
if (nx < 0 | nx >= N | ny < 0 | ny >= M) continue;
if (!visited[nx][ny] && map[nx][ny] != -1) {
count--;
visited[nx][ny] = true;
q.offer(new Node(nx, ny, cur.z + 1));
}
}
}
}
}
|
cs |
728x90
'Algorithm > BOJ' 카테고리의 다른 글
백준) 1449_수리공 항승 (0) | 2023.05.18 |
---|---|
백준) 7569_토마토2 (2) | 2023.05.17 |
백준) 2133_타일 채우기 (0) | 2023.05.16 |
백준) 11052_카드 구매하기 (0) | 2023.05.16 |
백준) 1074_Z (0) | 2023.05.16 |