




Sponsored
Sponsored
This approach involves using BFS to find the shortest path in an unweighted graph. BFS is well-suited for finding the shortest path because it explores all nodes at the present depth prior to moving on to nodes at the next depth level. By maintaining a queue that stores the current cell position and path length, we can efficiently determine the shortest path to the destination. Moreover, since the path can proceed in 8 possible directions, we must consider all potential moves from a given cell.
Time Complexity: O(n^2) because in the worst case, each cell of the n x n grid is visited once.
Space Complexity: O(n^2) due to the space needed to store the BFS queue.
1#include <vector>
2#include <queue>
3using namespace std;
4
5int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
6    int n = grid.size();
7    if (grid[0][0] != 0 || grid[n-1][n-1] != 0) return -1;
8    vector<pair<int, int>> directions = {{-1,-1}, {-1,0}, {-1,1}, {0,-1}, {0,1}, {1,-1}, {1,0}, {1,1}};
9    queue<tuple<int, int, int>> q;
10    q.push({0, 0, 1});
11    grid[0][0] = 1;
12    while (!q.empty()) {
13        auto [x, y, length] = q.front(); q.pop();
14        if (x == n-1 && y == n-1) return length;
15        for (auto [dx, dy] : directions) {
16            int nx = x + dx, ny = y + dy;
17            if (nx >= 0 && ny >= 0 && nx < n && ny < n && grid[nx][ny] == 0) {
18                q.push({nx, ny, length + 1});
19                grid[nx][ny] = 1;
20            }
21        }
22    }
23    return -1;
24}This solution utilizes BFS in a similar manner to the Python solution. It employs a queue to explore each cell in all 8 directions while marking visited cells to prevent revisits. The solution stops and returns the path length once the bottom-right corner is reached, or returns -1 if it’s not possible.
A* is a popular pathfinding and graph traversal algorithm. It is capable of focusing specifically on the shortest path with the use of heuristics. In this case, the heuristic is the Chebyshev distance between the current cell and the bottom-right corner, which matches the grid's 8-directional movement. By combining the BFS strategy with a heuristic score, A* ensures an efficient pathfinding solution while avoiding unnecessary paths.
Time Complexity: O(n^2 * log(n)) because each cell is processed once with priority queue operations.
Space Complexity: O(n^2) for the priority queue and grid storage.
1import heapq
2
3def This solution deploys the A* algorithm to find the shortest clear path by including a heuristic function, ensuring efficient traversal through the grid by prioritizing paths closer to the end point.