Skip to content

Commit 2a5de10

Browse files
committed
Feat: 그래프 미로 탐색(2178)
1 parent 9854710 commit 2a5de10

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
const fs = require("fs");
2+
const filePath =
3+
process.platform === "linux" ? "/dev/stdin" : `${__dirname}/input.txt`;
4+
let input = fs
5+
.readFileSync(filePath)
6+
.toString()
7+
.trim()
8+
.split("\n")
9+
.map((x) => x.trim());
10+
11+
const [n, m] = input
12+
.shift()
13+
.split(" ")
14+
.map((x) => +x);
15+
16+
const arr = input.map((x) => x.split(""));
17+
const visited = Array.from(Array(n), () => Array(m).fill(false));
18+
const dir = [
19+
[0, 1],
20+
[0, -1],
21+
[1, 0],
22+
[-1, 0],
23+
];
24+
bfs(0, 0, 1);
25+
26+
function bfs(i, j, count) {
27+
const queue = [[i, j, count]];
28+
visited[i][j] = true;
29+
30+
while (queue.length) {
31+
const [x, y, count] = queue.shift();
32+
33+
dir.forEach(([a, b]) => {
34+
const [nx, ny] = [x + a, y + b];
35+
36+
if (
37+
nx >= 0 &&
38+
ny >= 0 &&
39+
nx < n &&
40+
ny < m &&
41+
!visited[nx][ny] &&
42+
arr[nx][ny] === "1"
43+
) {
44+
visited[nx][ny] = true;
45+
queue.push([nx, ny, count + 1]);
46+
47+
if (nx === n - 1 && ny === m - 1) {
48+
console.log(count + 1);
49+
}
50+
}
51+
});
52+
}
53+
}

0 commit comments

Comments
 (0)