Given a 2D grid (maze) with obstacles, find the shortest path from a given source cell to a destination cell, moving only in four directions (up, down, left, right). Obstacles are represented by blocked cells. This is the classic Lee’s algorithm problem.
Lee’s algorithm uses BFS to find the shortest path in a grid, expanding all possible moves level by level. BFS guarantees the shortest path in an unweighted grid.
#include<vector>#include<queue>usingnamespace std;
classSolution {
public:int shortestPath(vector<vector<int>>& grid, pair<int,int> src, pair<int,int> dst) {
int n = grid.size(), m = grid[0].size();
vector<vector<bool>> vis(n, vector<bool>(m, false));
queue<pair<int,int>> q;
q.push(src); vis[src.first][src.second] = true;
int dist =0;
int dirs[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
while (!q.empty()) {
int sz = q.size();
while (sz--) {
auto [x, y] = q.front(); q.pop();
if (x == dst.first && y == dst.second) return dist;
for (auto& d : dirs) {
int nx = x + d[0], ny = y + d[1];
if (nx >=0&& ny >=0&& nx < n && ny < m &&!vis[nx][ny] && grid[nx][ny] ==0) {
vis[nx][ny] = true;
q.push({nx, ny});
}
}
}
++dist;
}
return-1;
}
};
classSolution:
defshortest_path(self, grid: list[list[int]], src: tuple[int,int], dst: tuple[int,int]) -> int:
from collections import deque
n, m = len(grid), len(grid[0])
vis = [[False]*m for _ in range(n)]
q = deque([src])
vis[src[0]][src[1]] =True dist =0 dirs = [(0,1),(1,0),(0,-1),(-1,0)]
while q:
for _ in range(len(q)):
x, y = q.popleft()
if (x, y) == dst:
return dist
for dx, dy in dirs:
nx, ny = x+dx, y+dy
if0<=nx<n and0<=ny<m andnot vis[nx][ny] and grid[nx][ny]==0:
vis[nx][ny] =True q.append((nx, ny))
dist +=1return-1