Problem
You are given an m x n
integer array grid
where grid[i][j]
could be:
1
representing the starting square. There is exactly one starting square.2
representing the ending square. There is exactly one ending square.0
representing empty squares we can walk over.-1
representing obstacles that we cannot walk over.
Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Backtracking with array modification and restoration
Here is the algo we can follow:
- First find out where to start (We dont need to find end yet, but we can do it while DFS)
- Also We need to know the number of empty cells, say
numEmpty
.
Then we start our dfs from start
such that our steps become equal tonumEmpty
.
We we try to explore a cell, it will change 0 to -1
(or some negative number) and do a dfs in 4 direction. (Another approach is is to use visited set)
If we hit the target and pass all empty cells, increment the result.
Why Are We Setting numEmpty
= 1 to Begin With?
That is to count the start element. Where we start from is kind of an empty place. Think about the situation of only two elements like [[1,2]]
, you will understand.
Blocking with -2
We can also set grid[i][j] = -2
and restore it to 0
. To differentiate at any time if we blocked the place for DFS. Then we have to change the condition:
|
|
To
|
|
Here is our DFS looks
Code
|
|
Complexity
- ⏰ Time complexity:
O(4^(m*n)
, wherem
is the number of rows andn
is the number of columns ingrid
. This is the worst-case scenario where nearly all cells are empty, and at each step, there are 4 different directions that can be chosen (up, down, left, right). - 🧺 Space complexity:
O(m*n)
- considering recursion stack, butO(1)
if we don’t consider it assuming array modification.
Method 2 - Backtracking With Visited Set
Here is the same with visited set.
Code
|
|