Skip to content

Commit 9f47b9b

Browse files
committed
게임 맵 최단거리 / 중급
1 parent 4cf5fdf commit 9f47b9b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
function solution(maps) {
2+
const n = maps.length;
3+
const m = maps[0].length;
4+
const directions = [
5+
[1, 0],
6+
[-1, 0],
7+
[0, 1],
8+
[0, -1],
9+
];
10+
const queue = [[0, 0]];
11+
const visited = Array.from({ length: n }, () => Array(m).fill(false));
12+
visited[0][0] = true;
13+
let count = 1;
14+
15+
while (queue.length > 0) {
16+
const size = queue.length;
17+
for (let i = 0; i < size; i++) {
18+
const [x, y] = queue.shift();
19+
20+
if (x === n - 1 && y === m - 1) {
21+
return count;
22+
}
23+
24+
for (const [dx, dy] of directions) {
25+
const nx = x + dx;
26+
const ny = y + dy;
27+
28+
if (
29+
nx >= 0 &&
30+
ny >= 0 &&
31+
nx < n &&
32+
ny < m &&
33+
maps[nx][ny] === 1 &&
34+
!visited[nx][ny]
35+
) {
36+
visited[nx][ny] = true;
37+
queue.push([nx, ny]);
38+
}
39+
}
40+
}
41+
count++;
42+
}
43+
44+
return -1;
45+
}

0 commit comments

Comments
 (0)