BOJ(Java)
자바(백준) 14940 쉬운 최단거리
자바생
2021. 11. 15. 12:32
728x90
오답 노트 & 새로 알게 된 점
기본적인 BFS 문제이다.
다만, 원래 갈 수 있는 땅 중에 가지 못하는 곳은 -1을 출력하고
원래 갈 수 없는 땅은 0을 출력해야한다.
이 조건식을 세울 줄 아느냐를 물어보는 문제인 것 같다.
원래 갈 수 있는 땅은 A[i][j] = 1을 뜻한다.
즉, A[i][j] 값이 1이면서 count[i][j] 가 0이면 -1을 출력하고,
나머지는 count[i][j]를 그대로 출력하면 된다.
코드
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
80
81
82
83
84
85
86
|
package bfs_dfs;
import java.io.*;
import java.util.*;
public class BOJ14940 {
static int atoi(String str) {
return Integer.parseInt(str);
}
static int n, m;
static int A[][];
static int count[][];
static boolean visit[][];
static Queue<Integer> q = new ArrayDeque<>();
static int dx[] = {-1, 1, 0, 0};
static int dy[] = {0, 0, 1, -1};
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
input();
pro();
print();
}
static void pro() {
while (!q.isEmpty()) {
int x = q.poll();
int y = q.poll();
for (int i = 0; i < 4; i++) {
int X = x + dx[i];
int Y = y + dy[i];
if(!isRangeTrue(X,Y)) continue;
if(visit[X][Y]) continue;
if(A[X][Y] == 0) continue;
q.offer(X);
q.offer(Y);
visit[X][Y] = true;
count[X][Y] = count[x][y] + 1;
}
}
}
static void print() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(A[i][j] != 0 && !visit[i][j]) sb.append(-1).append(" ");
else sb.append(count[i][j]).append(" ");
}
sb.append("\n");
}
System.out.print(sb);
}
static void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = atoi(st.nextToken());
m = atoi(st.nextToken());
A = new int[n][m];
count = new int[n][m];
visit = new boolean[n][m];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < m; j++) {
A[i][j] = atoi(st.nextToken());
if(A[i][j] == 2) {
q.offer(i);
q.offer(j);
visit[i][j] = true;
}
}
}
}
static boolean isRangeTrue(int x, int y) {
return x >= 0 & x < n && y >= 0 && y < m;
}
}
|
cs |
728x90