Skip to content

Instantly share code, notes, and snippets.

@kyleplo
Created June 29, 2022 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyleplo/14a8be4f28606e1b8d32755bba86c309 to your computer and use it in GitHub Desktop.
Save kyleplo/14a8be4f28606e1b8d32755bba86c309 to your computer and use it in GitHub Desktop.
Walls and Gates Solution
var maze = [
[Infinity, -1, 0, Infinity],
[Infinity, Infinity, Infinity, -1],
[Infinity, -1, Infinity, -1],
[0, -1, Infinity, Infinity]
];
var trackers = [];
maze.forEach((row, y) => {
row.forEach((column, x) => {
if(column === 0){
trackers.push({
x: x,
y: y,
distance: 0
});
}
});
});
function spawnTracker(x, y, distance){
if(maze[y] && maze[y][x] && maze[y][x] === Infinity){
maze[y][x] = distance;
newTrackers.push({
x: x,
y: y,
distance: distance
});
}
}
while(trackers.length){
var newTrackers = [];
trackers.forEach(tracker => {
spawnTracker(tracker.x + 1, tracker.y, tracker.distance + 1);
spawnTracker(tracker.x - 1, tracker.y, tracker.distance + 1);
spawnTracker(tracker.x, tracker.y + 1, tracker.distance + 1);
spawnTracker(tracker.x, tracker.y - 1, tracker.distance + 1);
});
trackers = newTrackers;
}
maze;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment