I been grinding leetcode using JavaScript and I was trying to solve this question https://leetcode.com/problems/shortest-path-in-binary-matrix/
This question was asking to return the distance or the length of the shortest path, and I solved it. Here is my answer
var shortestPathBinaryMatrix = function(grid) {
if(grid[0][0] != 0) return -1
const queue = [[[0,0], 1]]
const dest = [grid.length - 1, grid[0].length - 1]
const visited = new Set()
const getNextSteps = ([x,y]) => {
const dirs = [[1, 0], [-1, 0] , [0,1], [0,-1], [1,1], [-1,1], [-1,-1], [1,-1]]
const nextSteps = []
for(const [nx, ny] of dirs) {
if(grid[x + nx]?.[y + ny] == 0) nextSteps.push([x + nx, y + ny])
}
return nextSteps
}
for(const [curr, distance] of queue) {
if(visited.has(curr.toString())) continue
if(curr[0] === dest[0] && curr[1] === dest[1] && grid[dest[0]][dest[1]] == 0) return distance
visited.add(curr.toString())
getNextSteps(curr).forEach(adj => queue.push([adj, distance + 1]))
}
return -1
};
However I wonder if I can also get the actual paths it takes to reach the end of the matrix, so instead of returning a number as the length of the path, I want to return the actual paths which is an array of coordinates it visited on the shorted path.
For example, if the input grid is [[0,0,0],[1,1,0],[1,1,0]]
, it should return [ [ 0, 0 ], [ 0, 1 ], [ 1, 2 ], [ 2, 2 ] ]
But it is harder to do than it seems. I tried a few ways but I couldn't seem to solve it. Can anyone give it a try?