Problem
There is a robot on an m x n
grid. The robot is 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 either down or right at any point in time.
Given the two integers m
and n
, return all possible unique paths that the robot can take to reach the bottom-right corner.
Examples
Example 1:
|
|
Follow up
Imagine certain squares are “off limits”, such that the robot can not step on them. Design an algorithm to get all possible paths for the robot.
Refer Unique Paths in Grid 2-2 - Get all paths moving right or down with obstacles
Solution
Method 1 - Backtracking
We solved the similar question - Unique Paths in Grid 1 - Count all paths moving right or down, where we had to find the count of number of paths. Here we have to print the paths.
Code
|
|
Complexity
- ⏰ Time complexity:
O(2 ^ (m+n))
- 🧺 Space complexity:
O(m + n)
for recursive stack