Created
June 29, 2022 23:22
-
-
Save kyleplo/14a8be4f28606e1b8d32755bba86c309 to your computer and use it in GitHub Desktop.
Walls and Gates Solution
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
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