Check if destination is reachable by moving at most K step each time
Given a binary matrix grid of size M*N where ‘0‘ represents a blocked cell and ‘1’ represents a normal cell and a source (sx, sy) and destination (dx, dy). The task is to check if the destination is reachable from the source by moving at most K units of distance in a single step.
Input: M = 4, N = 4, grid = [[1, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], sx = 0, sy = 0, dx = 3, dy = 3, K = 3
Explanation: In this test case, the distance from the source to the destination is 3, which is less than or equal to K. Therefore, the destination is reachable.
Input: M = 4, N = 4, grid = [[1, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], sx = 0, sy = 0, dx = 3, dy = 3, K = 2
Explanation: In this test case, the distance from the source to the destination is 3, which is greater than K. Therefore, the destination is not reachable.
Approach: The above problem can be solved using the below idea:
Adding the source to the queue. Explore all the points that can be reached from the top point of the queue and add them to the queue along with the distance covered. Keep checking whether a point has been visited or not. If the destination point is reached return true, otherwise false.
Follow the below steps to implement the idea:
- Initialize an empty queue to store the cells we need to explore, and a 2D array to store the distance from the source for each cell.
- Add the source cell to the queue and set its distance to 0.
- While there are cells in the queue to explore:
- Get the next cell to explore from the queue.
- If the cell is the destination, return true.
- Otherwise, explore the cells that can be reached in one step from the current cell.
- For each valid and unexplored cell:
- Add the cell to the queue and update its distance from the source.
- If the distance from the source is greater than K, stop exploring this cell.
- If we have explored all the cells and have not found the destination, return false.
Below is the implementation of the above approach.
Time Complexity: O(M * N)
Auxiliary Space: O(M * N)
Please Login to comment...