LeetCode: Shortest Path In Binary Matrix Solution
1/**2 * @param {number[][]} grid3 * @return {number}4 */5var shortestPathBinaryMatrix = function (grid) {6 const N = grid.length7 const visited = Array.from({ length: N }, _ => Array(N).fill(false))8 const queue = []910 if (grid[0][0] || grid[N - 1][N - 1]) {11 return -112 }1314 visited[0][0] = true15 queue.unshift([0, 0, 1])16 while (queue.length) {17 const [x, y, shortest] = queue.pop()18 if (x === N - 1 && y === N - 1) {19 return shortest20 }21 for (const [i, j] of [22 [x - 1, y - 1],23 [x - 1, y],24 [x - 1, y + 1],25 [x, y - 1],26 [x, y + 1],27 [x + 1, y - 1],28 [x + 1, y],29 [x + 1, y + 1],30 ]) {31 if (0 <= i && i < N && 0 <= j && j < N && !grid[i][j] && !visited[i][j]) {32 visited[i][j] = true33 queue.unshift([i, j, shortest + 1])34 }35 }36 }3738 return -139}
Comments
Loading comments...
Tags
leetcode
graph
bfs
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.