Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 88bd5a5

Browse files
Create 게임-맵-최단거리.js
1 parent 0a50933 commit 88bd5a5

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎level-2/게임-맵-최단거리.js‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// https://programmers.co.kr/learn/courses/30/lessons/1844
2+
//정답 1 - prove-ability
3+
function solution(maps) {
4+
// BFS 활용
5+
const row = maps.length - 1, col = maps[0].length - 1;
6+
7+
// 큐 - 시작 위치 y, x, 이동 거리
8+
const queue = [[0, 0, 1]];
9+
10+
while(queue.length) {
11+
// 큐 추출
12+
let [y, x, count] = queue.shift();
13+
// 상대 팀 진영이라면
14+
if(y === row && x === col) return count;
15+
// 동서남북 확인
16+
for(let i = 0; i < 4; i++) {
17+
const [dy, dx] = DIRECTION[i];
18+
// 다음 길 위치
19+
const nextY = dy + y, nextX = dx + x;
20+
// 맵 밖으로 나간다면
21+
if(isRoad(nextY, nextX, row, col)) continue;
22+
// 도착한 곳이 벽이라면
23+
if(maps[nextY][nextX] === 0) continue;
24+
// 이미 지난 곳 벽으로 만들어서 다음에 접근 방지
25+
maps[nextY][nextX] = 0;
26+
// 다음에 확인해야하는 곳 큐에 추가
27+
// 갈수 있는 곳이 두 곳이라면 두 곳 추가됨
28+
queue.push([nextY, nextX, count + 1]);
29+
// 처음에 count 를 let 으로 선언하고 ++count 로 작성했을 떄 에러 발생 - 이유는 모르겠음..
30+
}
31+
}
32+
33+
return -1;
34+
}
35+
36+
// 상 우 하 좌
37+
const DIRECTION = [[1, 0], [0, 1], [-1, 0], [0, -1]];
38+
39+
// 사용이 가능한 길인지 확인하는 함수
40+
const isRoad = (nextY, nextX, row, col) => nextY < 0 || nextX < 0 || nextY > row || nextX > col;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /