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
- Q9.2 Find paths
- Q9.2
- Q9
- Q9.3 Find the magic index
- Cracking the coding interview--Q9.2
- Cracking the coding interview--Q9.2
- find: paths must precede expression
- Paths - 2
- Q9.1
- Q9.3
- Q9.5
- Q9.6
- Q9.7
- Leetcode Q9
- How to Find Suspicious Access Paths
- find . -name *.c find: paths must precede expression:
- find out gcc/clang head file search paths
- find:paths must precede expression问题及解决
- 使用XFire+Spring构建Web Service(一)——helloWorld篇
- poj 1573 模拟
- 堆和栈的区别
- Kali Mysql 登录失败:MySQL - ERROR 2002 (HY000): Can't connect to local MySQL server through socket
- [Leetcode 165, Easy] Compare Version Numbers
- Q9.2 Find paths
- thinkphp3.2.2生成mysql3级数据库城市和js数组
- js调试
- 【实例应用】DATATable那些事儿
- [C++]LeetCode: 120 Permutations II
- Python标准库:内置函数min(iterable, *[, key, default])
- 在图像需要位置画方框_opencv(1)
- 物体的移动方式(转载)
- 云计算设计模式翻译(二):Circuit Breaker Pattern(断路器模式)