Created
August 7, 2021 16:49
-
-
Save galElmalah/68d85c01ab707caac58f4fc3d34b4b33 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cases = require('./cases'); | |
const caseRunner = require('../../utils/caseRunner'); | |
const parse = (input) => { | |
return input | |
.split('\n') | |
.filter(Boolean) | |
.map((r) => r.split('')); | |
}; | |
const id = (i, j) => `${i},${j}`; | |
const findStartAndEndCords = (grid) => { | |
let s; | |
let e; | |
for (let i = 0; i < grid.length; i++) { | |
for (let j = 0; j < grid[0].length; j++) { | |
if (grid[i][j] === 'A') { | |
s = [i, j]; | |
} | |
if (grid[i][j] === 'B') { | |
e = [i, j]; | |
} | |
} | |
} | |
return [s, e]; | |
}; | |
const backtrackPath = (nodeId, paths) => { | |
if (!paths.has(nodeId)) { | |
return ''; | |
} | |
return backtrackPath(paths.get(nodeId).nodeId, paths) + paths.get(nodeId).d; | |
}; | |
const Labyrinth = (raw) => { | |
const grid = parse(raw); | |
let [[si, sj], [ei, ej]] = findStartAndEndCords(grid); | |
const di = [0, 0, 1, -1]; | |
const dj = [-1, 1, 0, 0]; | |
const dirs = ['L', 'R', 'D', 'U']; | |
const Q = []; | |
Q.push([si, sj]); | |
const discovered = new Set(); | |
discovered.add(id(si, sj)); | |
const paths = new Map(); | |
while (Q.length) { | |
const [ci, cj] = Q.shift(); | |
if (ci === ei && cj === ej) { | |
const path = backtrackPath(id(ei, ej), paths); | |
return ['YES', path.length, path]; | |
} | |
for (let i = 0; i < 4; i++) { | |
const nodeId = id(ci + di[i], cj + dj[i]); | |
if ( | |
grid[ci + di[i]] && | |
grid[ci + di[i]][cj + dj[i]] && | |
(grid[ci + di[i]][cj + dj[i]] === '.' || | |
grid[ci + di[i]][cj + dj[i]] === 'B') && | |
!discovered.has(nodeId) | |
) { | |
paths.set(nodeId, { d: dirs[i], nodeId: id(ci, cj) }); | |
discovered.add(nodeId); | |
Q.push([ci + di[i], cj + dj[i]]); | |
} | |
} | |
} | |
return 'NO'; | |
}; | |
caseRunner(Labyrinth, cases); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment