|
| 1 | +// 출발점부터 빠르게 레버있는 곳으로 간 후, 다시 레버에서 탈출구로 가는 것 목표. 못가면 -1 반환 |
| 2 | +const solution = (maps) => { |
| 3 | + const dir = [ |
| 4 | + [0, 1], |
| 5 | + [0, -1], |
| 6 | + [1, 0], |
| 7 | + [-1, 0], |
| 8 | + ] |
| 9 | + const n = maps.length |
| 10 | + const m = maps[0].length |
| 11 | + let S, L, E |
| 12 | + // 시작, 레버, 출구 위치 저장하고 |
| 13 | + // 시작 - 레버 / 레버 - 출구 경로의 최단경로 더하기 |
| 14 | + maps = maps.map((row, x) => { |
| 15 | + row = row.split("") |
| 16 | + row.forEach((item, y) => { |
| 17 | + if (item === "S") S = [x, y] |
| 18 | + if (item === "L") L = [x, y] |
| 19 | + if (item === "E") E = [x, y] |
| 20 | + }) |
| 21 | + return row |
| 22 | + }) |
| 23 | + |
| 24 | + const bfs = (start, end) => { |
| 25 | + const visited = Array.from({ length: n }, () => Array(m).fill(false)) |
| 26 | + const q = [[...start, 0]] |
| 27 | + |
| 28 | + while (q.length) { |
| 29 | + let [x, y, dist] = q.shift() |
| 30 | + if (x === end[0] && y === end[1]) return dist |
| 31 | + |
| 32 | + for (let [dx, dy] of dir) { |
| 33 | + let [nx, ny] = [x + dx, y + dy] |
| 34 | + if (nx >= 0 && nx < n && ny >= 0 && ny < m) { |
| 35 | + if (!visited[nx][ny] && maps[nx][ny] !== "X") { |
| 36 | + visited[nx][ny] = true |
| 37 | + q.push([nx, ny, dist + 1]) |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return -1 |
| 44 | + } |
| 45 | + |
| 46 | + let toL = bfs(S, L) |
| 47 | + if (toL === -1) return -1 |
| 48 | + let toE = bfs(L, E) |
| 49 | + if (toE === -1) return -1 |
| 50 | + |
| 51 | + return toL + toE |
| 52 | +} |
0 commit comments