leetcode 63. Unique Paths II
一、问题描述
机器人位于一个m x n网格的左上角。机器人只能随时向下或向右移动。机器人正在尝试到达网格的右下角。假设网格中有障碍物,求有多少条独特的路径?ps:网格中的障碍物和空白区分别标记为1和0。
【举例】
输入:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
输出: 2
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
二、解题算法
1、方法一:dfs+备忘录
/*************************************************
Author:tmw
date:2018-5-10
*************************************************/
#include <stdio.h>
#include <stdlib.h>
/**方法一:dfs+备忘录**/
int result[1000][1000] = {0};
int dfs_Memo( int** array, int row, int col )
{
if( row < 1 || col < 1 ) return 0; /**边界限定**/
if( array[row-1][col-1] == 1 ) return 0; /**遇到障碍**/
if( row == 1 && col == 1 ) return 1; /**起始条件**/
if( result[row][col]>0 ) return result[row][col];
else
result[row][col] = dfs_Memo(array, row-1, col)+dfs_Memo(array,row,col-1);
return result[row][col];
}
int uniquePathsWithObstacles(int** obstacleGrid, int obstacleGridRowSize, int obstacleGridColSize)
{
return dfs_Memo(obstacleGrid,obstacleGridRowSize,obstacleGridColSize);
}
2、方法二:动态规划
/**方法二:动态规划**/
int uniquePathsWithObstacles(int** obstacleGrid, int obstacleGridRowSize, int obstacleGridColSize)
{
/**当一开始就有障碍或者目标处就是障碍,根本走不到,则直接返回0**/
if( obstacleGrid[0][0] == 1 || obstacleGrid[obstacleGridRowSize-1][obstacleGridColSize-1] == 1 ) return 0;
int result[1000] = {0};
result[0] = 1;
int i,j;
for( i=0; i<obstacleGridRowSize; i++ )
{
for( j=0; j<obstacleGridColSize; j++ )
{
/**如果是障碍**/
if( obstacleGrid[i][j] == 1 )
result[j] = 0;
/**如果不是障碍**/
else
{
/**j==0时只有一列,保持当下的走法数**/
if( j==0 )
result[j] = result[j];
else
result[j] = result[j]+result[j-1];
}
}
}
return result[obstacleGridColSize-1];
}
梦想还是要有的,万一实现了呢~~~ヾ(◍°∇°◍)ノ゙~~~~