![]() |
VOOZH | about |
Given a matrix mat[][] of size n × n, where mat[i][j] represents the maximum number of steps a rat can jump either forward (right) or downward from that cell, find a path for the rat to reach from the top-left cell (0, 0) to the bottom-right cell (n - 1, n - 1). A cell containing 0 is blocked and cannot be used in the path.
Return an n × n matrix where 1 represents the cells included in the path and 0 represents the remaining cells.
Note: If multiple valid paths exist, choose the path with the shortest possible jumps first. For the same jump length, moving forward (right) should be preferred over moving downward.
Examples:
Input: mat[][] = [[2, 1, 0, 0],
[3, 0, 0, 1],
[0, 1, 0, 1],
[0, 0, 0, 1]]
Output: [[1, 0, 0, 0],
[1, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1]]
Explanation:
The rat starts from cell (0, 0) which contains value 2, so it can jump at most 2 steps either right or downward.
It first tries moving right to (0, 1), but this path does not lead to the destination.
The rat then moves downward to (1, 0) which contains value 3.
From this cell, it jumps 3 steps to the right and reaches (1, 3).
Since (1, 3) contains value 1, the rat can move downward one step at a time to (2, 3) and finally to (3, 3), which is the destination cell.Input: mat[][] = [[2, 1, 0, 0],
[2, 0, 0, 1],
[0, 1, 0, 1],
[0, 0, 0, 1]]
Output: [[-1]]
Explanation:
The rat starts from cell (0, 0) which contains value 2, so it can jump at most 2 steps either right or downward.
However, every possible path eventually gets blocked by cells containing 0, making it impossible to reach the destination cell (3, 3).
Therefore, no valid path exists and the output is [[-1]].
Table of Content
The idea is to explore all possible paths from (0,0) to (n-1,n-1) using recursive traversal while ensuring each move stays within bounds, avoids blocked cells, and prevents revisiting. At each step, it prioritizes moving right first, then down, attempting all possible jumps allowed by the current cell. If a path reaches the destination, it returns the path matrix; otherwise, it backtracks and explores alternatives. If no valid path exists, it returns -1.
1 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1
The idea is to use recursion and backtracking to find a valid path from the top-left cell to the bottom-right cell. From each cell, jumps from
1to the cell value are tried first toward the right and then downward. Memoization is used to avoid recomputing already visited states, while backtracking helps mark and unmark the current path in the answer matrix.
(0,0)1 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1