https://school.programmers.co.kr/learn/courses/30/lessons/159993
function solution(maps) {
const bfs = (s, e) => {
const [width, height] = [maps.length, maps[0].length],
[queue, valueVisit] = [[], maps.map((e) => [...e].map((v) => 0))];
const [dirX, dirY] = [[0, 0, -1, 1], [-1, 1, 0, 0]];
queue.push([s[0], s[1]]);
while (queue.length) {
const [x, y] = queue.shift();
for (let i = 0; i < 4; ++i) {
const [nx, ny] = [x + dirX[i], y + dirY[i]];
if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;
if (maps[nx][ny] === "X") continue;
if (valueVisit[nx][ny] && valueVisit[x][y] + 1 >= valueVisit[nx][ny]) continue;
valueVisit[nx][ny] = valueVisit[x][y] + 1;
queue.push([nx, ny]);
}
}
return valueVisit[e[0]][e[1]] === 0 ? -1 : valueVisit[e[0]][e[1]];
};
const pos = maps.reduce((acc, e, i) => ([...e].forEach((v, j) => {
if (["S", "L", "E"].includes(v)) acc[v] = [i, j];
}), acc), {});
const [dist1, dist2] = [bfs(pos["S"], pos["L"]), bfs(pos["L"], pos["E"])];
return dist1 < 0 || dist2 < 0 ? -1 : dist1 + dist2;
}
'Coding Test > Programmers' 카테고리의 다른 글
[Programmers] Lv 2. 디펜스 게임 (0) | 2023.04.19 |
---|---|
[Programmers] (그리디. Greedy) Lv 2. 광물 캐기 (0) | 2023.04.18 |
[Programmers] Lv 2. N-Queen (0) | 2023.04.10 |
[Programmers] Lv 2. 연속된 부분 수열의 합 (0) | 2023.04.07 |
[Programmers] Lv 2. 테이블 해시 함수 (0) | 2023.04.07 |
댓글