BOJ(Java)
자바(백준) 1261 알고스팟
자바생
2021. 12. 28. 18:15
728x90
오답 노트 & 새로 알게 된 점
이 문제는 (N,M)의 최소 경로가 아닌 벽을 최소로 부수면서 (N,M)에 도착해야한다.
가중치가 0 또는 1이기 때문에 일반적인 BFS를 사용할 수 없다. ( 0-1 BFS 라는 것이 있다)
따라서 가중치가 0을 포함하는 양수일 때 사용하는 알고리즘인 다익스트라를 사용한다.
방문처리는 dist의 값이 현재 방문할 dist값보다 크거나 같게 되면 continue를 한다.
코드
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
|
import java.io.*;
import java.util.*;
public class Main {
static int atoi(String str) {
return Integer.parseInt(str);
}
static int row, col;
static int A[][];
static int dist[][];
static int dx[] = {0, 0, 1, -1};
static int dy[] = {1, -1, 0, 0};
public static void main(String[] args) throws IOException {
input();
pro();
}
static void pro() {
bfs();
System.out.println(dist[row - 1][col - 1]);
}
static void bfs() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
dist[i][j] = Integer.MAX_VALUE;
}
}
Queue<Integer> q = new ArrayDeque<>();
q.offer(0);
q.offer(0);
dist[0][0] = 0;
while (!q.isEmpty()) {
int x = q.poll();
int y = q.poll();
for (int i = 0; i < 4; i++) {
int dX = x + dx[i];
int dY = y + dy[i];
if(!isRangeTrue(dX, dY)) continue;
if(dist[x][y] + A[dX][dY] >= dist[dX][dY]) continue;
dist[dX][dY] = dist[x][y] + A[dX][dY];
q.offer(dX);
q.offer(dY);
}
}
/* for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(dist[i][j] + " ");
}
System.out.println();
}*/
}
static boolean isRangeTrue(int x, int y) {
return x >= 0 && x < row && y >= 0 && y < col;
}
static void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
col = atoi(st.nextToken());
row = atoi(st.nextToken());
dist = new int[row][col];
A = new int[row][col];
for (int i = 0; i < row; i++) {
String str = br.readLine();
for (int j = 0; j < col; j++) {
A[i][j] = str.charAt(j) - '0';
}
}
}
}
|
cs |
728x90