![]() |
VOOZH | about |
Given a grid of size NXN, some of the cells are vacant and some are blocked. We can move to any horizontally or vertically adjacent cell if the cell is vacant. Also, we can jump to a vacant cell in the 5×5 area centered at the square we are currently in. Starting from the cell (r1, c1), find the minimum number of jumps to reach cell (r2, c2). A vacant cell is denoted by '.' and a blocked cell is denoted by '#'.
Note: We cannot move outside the grid.
Example:
Input: numRows = 4, numCols = 4, startRow = 2, startCol = 2, endRow = 3, endCol = 3,
grid = { {'.', '.', '.', '.'},
{'.', '.', '.', '.'},
{'.', '.', '.', '.'},
{'.', '.', '.', '.'} };
Output: 0Input: numRows = 4, numCols = 4, startRow = 1, startCol = 1, endRow = 4, endCol = 4
grid = { {'.', '.', '#', '.'},
{'.', '.', '#', '.'},
{'.', '#', '.', '.'},
{'.', '#', '.', '.'} };
Output: 1
Approach:
To idea is to use use Breadth-First Search (BFS) to explore the grid based on the idea of minimizing the number of jumps. The grid can be categorized into regions based on the required number of jumps, such as 0 jumps, 1 jump, and so on.
Start a BFS from the initial cell and enumerating the squares that can be newly reached with a cost of 0. Then, from the squares reached with a cost of 0, identify squares that can be reached by using Move B (jumps) and are not reachable with a cost less than or equal to 0. Continue this process, enumerating squares based on increasing costs.
To optimize the implementation, we can use 01-BFS when the cost of a move is either 0 or 1. This involves using a deque, pushing vertices that can be moved to with a cost of 0 to the front of the deque and vertices that can be moved to with a cost of 1 to the back. This allows for searching in the order of distances.
It's essential to note that if a vertex added with a cost of 1 is later added only with a cost of 0, the same vertex may be added twice. Therefore, careful consideration is required during the implementation to avoid such duplications.
Step-by-step appraoch:
Below is the implementation of the above approach:
1
Time Complexity: O(n*m), where n be the number of rows and m be the number of columns in the grid.
Auxiliary Space: O(n*m)