⬅ Previous Topic
Dijkstra’s Algorithm Using Priority QueueNext Topic ⮕
Path With Minimum Effort in Grid using Graphs⬅ Previous Topic
Dijkstra’s Algorithm Using Priority QueueNext Topic ⮕
Path With Minimum Effort in Grid using GraphsTopic Contents
Given an n × m
binary matrix grid
where each cell can be either 0
or 1
, find the shortest path between a source cell and a destination cell. You can only move to a cell with value 1
and you may move only in four directions: up, down, left, and right.
If the path between the source and destination is not possible, return -1
.
Note: The source and destination cells must also be 1
to begin with, or the path is impossible.
0
. If yes, return -1
.dist
with Infinity
. Set the distance for the source cell to 0
.(x, y)
and its distance d
.(nx, ny)
.(nx, ny)
is within bounds, has value 1
, and not yet visited or has a longer distance:dist[nx][ny]
= d+1
.(nx, ny, d+1)
.dist[destX][destY]
.-1
.function shortestPathBinaryMaze(grid, source, destination) {
const [n, m] = [grid.length, grid[0].length];
const [srcX, srcY] = source;
const [destX, destY] = destination;
if (grid[srcX][srcY] === 0 || grid[destX][destY] === 0) return -1;
const directions = [[0,1],[1,0],[0,-1],[-1,0]];
const dist = Array.from({ length: n }, () => Array(m).fill(Infinity));
dist[srcX][srcY] = 0;
const queue = [[srcX, srcY, 0]];
while (queue.length > 0) {
const [x, y, d] = queue.shift();
for (const [dx, dy] of directions) {
const [nx, ny] = [x + dx, y + dy];
if (nx >= 0 && ny >= 0 && nx < n && ny < m && grid[nx][ny] === 1 && d + 1 < dist[nx][ny]) {
dist[nx][ny] = d + 1;
queue.push([nx, ny, d + 1]);
}
}
}
return dist[destX][destY] === Infinity ? -1 : dist[destX][destY];
}
const grid = [[1,1,1],[0,1,0],[1,1,1]];
console.log("Shortest Distance:", shortestPathBinaryMaze(grid, [0,0], [2,2])); // Output: 4
⬅ Previous Topic
Dijkstra’s Algorithm Using Priority QueueNext Topic ⮕
Path With Minimum Effort in Grid using GraphsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.