백준 25416번 : 빠른 숫자 탐색 (이동 거리 기록)
이번 문제는 5x5 크기의 보드에서 특정 좌표 (r,c)에서 부터 1까지의 거리를 측정하는 문제이다.
단순하게 BFS를 실행시켜 풀었으며 크게 설명할 부분은 없다.
다만, 거리를 어떻게 측정해야하는지 이번 문제를 풀면서 헷갈려서 다음 번에 참고하기 위해 전체 소스코드만 기록할 것이다.
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
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int r, c;
static int[][] arr;
static boolean[][] visited;
static int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
public static void main(String[] args) throws java.io.IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
arr = new int[5][5];
visited = new boolean[5][5];
for (int i = 0; i < 5; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < 5; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
st = new StringTokenizer(br.readLine());
r = Integer.parseInt(st.nextToken());
c = Integer.parseInt(st.nextToken());
System.out.println(bfs());
}
public static int bfs() {
Queue<int[]> q = new LinkedList<>();
q.offer(new int[]{r,c, 0});
visited[r][c] = true;
while (!q.isEmpty()) {
int[] cur = q.poll();
int dist = cur[2];
if (arr[cur[0]][cur[1]] == 1) {
return dist;
}
for (int i = 0; i < 4; i++) {
int nx = cur[0] + dx[i];
int ny = cur[1] + dy[i];
if (nx >= 0 && ny >= 0 && nx < 5 && ny < 5) {
if ((arr[nx][ny] == 0 || arr[nx][ny] == 1) && !visited[nx][ny]) {
q.offer(new int[]{nx, ny, dist + 1});
visited[nx][ny] = true;
}
}
}
}
return -1;
}
}
bfs 함수를 보면 큐에 시작 좌표를 넣으면서 동시에 거리에 대한 정보도 추가했다.
이 거리를 담고 있는 dist 변수를 활용해 거리를 재면 된다.
이 블로그는 저작권자의 CC BY 4.0 라이센스를 따릅니다.