Skip to content

Commit 637c8e9

Browse files
committed
add: 백준/벽 부수고 이동하기 1
1 parent b402060 commit 637c8e9

1 file changed

Lines changed: 97 additions & 0 deletions

File tree

boj/2206(BFS).js

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
// 벽 부수고 이동하기
2+
// https://www.acmicpc.net/problem/2206
3+
4+
const fs = require('fs');
5+
const stdin = (process.platform === 'linux'
6+
? fs.readFileSync('/dev/stdin').toString().trim()
7+
: `6 4
8+
0100
9+
1110
10+
1000
11+
0000
12+
0111
13+
0000
14+
`
15+
).split('\n');
16+
17+
const input = (() => {
18+
let line = 0;
19+
return () => stdin[line++];
20+
})();
21+
22+
const [N, M] = input()
23+
.split(' ')
24+
.map((each) => parseInt(each));
25+
26+
const arr = [];
27+
const visited = [];
28+
29+
for (let row = 0; row < N; row++) {
30+
const col = input()
31+
.split('')
32+
.map((each) => parseInt(each));
33+
arr.push(col);
34+
visited.push(
35+
Array(M)
36+
.fill()
37+
.map(() => Array(1).fill(0))
38+
);
39+
}
40+
41+
const dy = [1, -1, 0, 0];
42+
const dx = [0, 0, -1, 1];
43+
44+
function bfs() {
45+
visited[0][0][0] = 1;
46+
47+
const q = [[0, 0, 0]];
48+
49+
while (q.length !== 0) {
50+
const [y, x, w] = q.shift();
51+
52+
if (y === N - 1 && x === M - 1) {
53+
return visited[N - 1][M - 1][w];
54+
}
55+
56+
for (let i = 0; i < 4; i++) {
57+
const ny = y + dy[i];
58+
const nx = x + dx[i];
59+
const nw = w + 1;
60+
61+
if (ny < 0 || ny >= N || nx < 0 || nx >= M) {
62+
continue;
63+
}
64+
65+
if (visited[ny][nx][w]) {
66+
continue;
67+
}
68+
69+
if (arr[ny][nx] === 0) {
70+
visited[ny][nx][w] = visited[y][x][w] + 1;
71+
q.push([ny, nx, w]);
72+
}
73+
74+
if (arr[ny][nx] === 1 && nw <= 1) {
75+
visited[ny][nx][nw] = visited[y][x][w] + 1;
76+
q.push([ny, nx, nw]);
77+
}
78+
}
79+
}
80+
81+
return -1;
82+
}
83+
84+
console.log(bfs());
85+
86+
/*
87+
88+
## How
89+
최단거리를 구하는 문제이므로 BFS를 사용한다. 만약 가중치가 있는 최단경로라면 다익스트라를 사용해야 한다.
90+
91+
visited 배열에 벽을 부쉈는지 여부를 포함시키는 것이 핵심이었다. 즉 3차원 배열을 만들어야 했다.
92+
93+
벽을 부순적이 있는지에 대한 조건을 포함하여 벽인지 아닌지를 판별해 (M - 1, N - 1)까지 도착했을 때 visited 배열에 캐싱한 값을 출력하도록 하면 된다.
94+
95+
## Retrospective
96+
97+
*/

0 commit comments

Comments
 (0)