Problem Description
Given an m x n grid where:
- 1 represents the starting square.
- 2 represents the ending square.
- 0 represents empty squares that can be walked over.
- -1 represents obstacles. Return the number of 4-directional paths from the start to the end that visit every non-obstacle square exactly once.
Key Insights
- Count all non-obstacle cells (including start and end) to know the route length required.
- Use Depth First Search (DFS) to explore all possible paths from the starting cell.
- Mark cells as visited during recursion to avoid revisiting and backtrack afterwards.
- Only count a path when reaching the ending cell and the number of visited cells equals the total non-obstacle count.
Space and Time Complexity
Time Complexity: O(3^(mn)) in the worst-case scenario due to branching factor in DFS. Space Complexity: O(mn) due to recursion call stack and in-place modifications of the grid.
Solution
We solve the problem by performing a DFS starting from the unique starting cell. Before DFS, count the total number of non-obstacle cells. As DFS explores neighbors recursively, mark the cell as visited (by setting it to -1) to prevent cycles and restore its value after exploring (backtracking). When the ending cell is reached, check if we have visited all non-obstacle cells. If yes, increment the valid path count.
Data structures and algorithms used:
- Recursion (DFS) for exploring all valid paths.
- In-place grid marking for tracking visited cells.
- Backtracking for restoring grid state. This approach ensures that every possible valid route is considered while correctly handling obstacles and ensuring each non-obstacle cell is visited exactly once.