




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.
1from collections import deque
2
3def shortestPathBinaryMatrix(grid):
4    n = len(grid)
5    if grid[0][0] != 0 or grid[n-1][n-1] != 0:
6        return -1
7    directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
8    queue = deque([(0, 0, 1)])
9    grid[0][0] = 1  # Visited
10    while queue:
11        x, y, length = queue.popleft()
12        if x == n-1 and y == n-1:
13            return length
14        for dx, dy in directions:
15            nx, ny = x + dx, y + dy
16            if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] == 0:
17                queue.append((nx, ny, length + 1))
18                grid[nx][ny] = 1  # Mark as visited
19    return -1The function shortestPathBinaryMatrix uses BFS to explore each adjacent cell of the current cell in all 8 possible directions. The grid has been marked to indicate which cells have been visited, avoiding revisiting them and ensuring efficient path finding. If the bottom-right corner is reached, the function returns the path length; otherwise, it returns -1 if no path exists.
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.