Matrix Depth-First Search (DFS) for Unique Paths
Problem: Count unique paths from the top-left to bottom-right of a matrix, avoiding obstacles (1s) and not revisiting cells in the same path.
1. Approach
- DFS with Backtracking:
- Explore all four directions (up, down, left, right).
- Track visited cells to avoid cycles.
- Use recursion to traverse paths and backtrack to reset visited cells.
2. Algorithm
Base Cases
- Out of Bounds: Row/column < 0 or ≥ matrix dimensions.
- Obstacle: Current cell is
1.
- Visited Cell: Revisiting a cell in the current path.
- Destination Reached: Bottom-right cell.
Steps
- Check Base Cases: Return
0 for invalid paths or 1 if destination is reached.
- Mark Current Cell as Visited.
- Recursively Explore Directions:
- Up:
(row-1, col)
- Down:
(row+1, col)
- Left:
(col-1, row)
- Right:
(col+1, row)
- Sum Valid Paths from all directions.
- Unmark Current Cell (backtracking).
3. Code Implementation