Unique Paths I
Question
A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
How many possible unique paths are there?
Analysis
最左侧和最上侧的一列的行走方式都只有1种,除此之外的每个格子的路径个数是他的上方相邻格和左侧相邻格的路径个数和
Code
2-D array version:
|
|
1-D array version:
|
|
Unique Paths II
Question
Follow up for “Unique Paths”:
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1
and 0
respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
|
|
The total number of unique paths is 2
.
Analysis
重点在于确定好最左侧和最上方行列的路径个数
- (0,0)位置有阻碍则map为0,否则为1
- 左侧和上方的当前格子路径个数都等于前一个*1,即假如上一个格子的路径数已经为0,其后所有的格子的路径数都为0
- 其余格子计算同上
Code
|
|
####