https://www.geeksforgeeks.org/minimum-steps-to-reach-any-of-the-boundary-edges-of-a-matrix-set-2/
https://www.geeksforgeeks.org/minimum-steps-to-reach-any-of-the-boundary-edges-of-a-matrix/
DFS + cache
Given an N X M matrix, where ai, j = 1 denotes the cell is not empty, ai, j = 0 denotes the cell is empty and ai, j = 2, denotes that you are standing at that cell. You can move vertically up or down and horizontally left or right to any cell which is empty. The task is to find the minimum number of steps to reach any boundary edge of the matrix. Print -1 if not possible to reach any of the boundary edges.
Note: There will be only one cell with value 2 in the entire matrix.
Examples:
Input: matrix[] = {1, 1, 1, 0, 1} {1, 0, 2, 0, 1} {0, 0, 1, 0, 1} {1, 0, 1, 1, 0} Output: 2 Move to the right and then move upwards to reach the nearest boundary edge.
- Find the index of the ‘2’ in the matrix.
- Check if this index is a boundary edge or not, if it is, then no moves are required.
- Insert the index x and index y of ‘2’ in the queue with moves as 0.
- Use a 2-D vis array to mark the visiting positions in the matrix.
- Iterate till the queue is empty or we reach any boundary edge.
- Get the front element(x, y, val = moves) in the queue and mark vis[x][y] as visited. Do all the possible moves(right, left, up and down) possible.
- Re-insert val+1 and their indexes of all the valid moves to the queue.
- If the x and y become the boundary edges any time return val.
- If all the moves are made, and the queue is empty, then it is not possible, hence return -1.
Time Complexity: O(N^2)
Auxiliary Space: O(N^2)
Auxiliary Space: O(N^2)
DFS + cache
Approach: The problem can be solved using a Dynamic Programming approach. Given below is the algorithm to solve the above problem.
- Find the position which has ‘2’ in the matrix.
- Initialize two 2-D arrays of size same as the matrix. The dp[][] which stores the minimum number of steps to reach any index i, j and vis[][] marks if any particular i, j position has been visited or not previously.
- Call the recursive function which has the base case as follows:
- if the traversal at any point reaches any of the boundary edges return 0.
- if the points position n, m has stored the minimum number of steps previously, then return dp[n][m].
- Call the recurion again with all possible four moves that can be done from the position n, m. The moves are only possible if mat[n][m] is 0 and the position has not been visited previously.
- Store the minimal of the four moves.
- If the recursion returns any value less than 1e9, which we had stored as the maximum value, then there is an answer, else it does not have any answer.