Q9.2 Find paths

来源:互联网 发布:淘宝怎么发帖 编辑:程序博客网 时间:2024/04/28 08:43
Q:

Imagine a robot sitting on the upper left hand corner of an NxN grid. The robot can only move in two directions: right and down. How many possible paths are there for the robot?

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.

A: 标准的DP问题,转移方程: f[i][j] = f[i-1][j] + f[i][j-1]

#include <iostream>#include <vector>using namespace std;int getPath(int m, int n) {vector<int> f(n,0);f[0] =  1;for (int i = 0; i < m; i++) {for (int j = 1; j < n; j++) {f[j] += f[j-1];}}return f[n-1];}int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {    const int m = obstacleGrid.size();    if (m == 0) {        return 0;    }    const int n = obstacleGrid[0].size();    if (obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1) {        return 0;    }    int f[n+1];    fill_n(&f[0], n+1, 1);    f[0] = 0;    int i = 0;    for (i = 1; i <= n; i++) {        if (obstacleGrid[0][i-1] == 1) {            f[i] = 0;            break;        }    }    for (int j = i; j <= n; j++) {        f[j] = 0;    }    for (int i = 2; i <= m; i++) {        for (int j = 1; j <= n; j++) {            f[j] = obstacleGrid[i-1][j-1]?0:f[j]+f[j-1];        }    }    return f[n];}int main() {cout<<getPath(3,3)<<endl;vector<vector<int> > obstacleGrid(3, vector<int>(3,0));obstacleGrid[1][1] = 1;cout<<uniquePathsWithObstacles(obstacleGrid)<<endl;return 0;}


 

0 0