Problem
You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m-1][n-1]). The robot can only move in any four directions(up, down, right, left) at any point in time.
An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle.
Return all possible unique paths that the robot can take to reach the bottom-right corner.
This problem is similar to Unique Paths in Grid - Get all paths moving right or down with obstacles but robot can move in all 4 directions.
Examples
Example 1:
There is one obstacle in the middle of a 3x3 grid as illustrated below.
| |
Example 2:
| |
Solution
Naive Algorithm The Naive Algorithm is to generate all paths from source to destination and one by one check if the generated path satisfies the constraints.
| |
Method 1 - Backtracking Algorithm
- We initialize
resultto an empty list that will eventually contain all unique valid paths. - We check if the starting or ending cell is an obstacle. If so, we immediately return the empty list.
- We use a
visitedboolean array to make sure that we do not include any cell more than once in the same path. - The
backtrackmethod explores all four directions recursively. After exploring, we undo the step (backtrack) so we can explore different paths. - When we reach the bottom-right corner of the
grid, we add the currentpathto our result list.
Code
| |
Complexity
- ⏰ Time complexity:
O(4^(m*n)) - 🧺 Space complexity:
O(m*n)