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


2. Algorithm

Base Cases

  1. Out of Bounds: Row/column < 0 or ≥ matrix dimensions.
  2. Obstacle: Current cell is 1.
  3. Visited Cell: Revisiting a cell in the current path.
  4. Destination Reached: Bottom-right cell.

Steps

  1. Check Base Cases: Return 0 for invalid paths or 1 if destination is reached.
  2. Mark Current Cell as Visited.
  3. Recursively Explore Directions:
  4. Sum Valid Paths from all directions.
  5. Unmark Current Cell (backtracking).

3. Code Implementation