• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

CCI 9.2 机器人移动路径

mysql 搞代码 4年前 (2022-01-09) 25次浏览 已收录 0个评论

摄像有个机器人坐在X*Y网的左上角,只能想右、向下移动。机器人从(0,0)到(X,Y)有多少种走法? 进阶 假设有些点为“禁区”,机器人不能踏足。设计一种算法,找出一条路径,让机器人从左上角移动到右下角。 这道题跟LeetCode上的Unique Paths 和Unique Paths I

摄像有个机器人坐在X*Y网格的左上角,只能想右、向下移动。机器人从(0,0)到(X,Y)有多少种走法?

进阶

假设有些点为“禁区”,机器人不能踏足。设计一种算法,找出一条路径,让机器人从左上角移动到右下角。

这道题跟LeetCode上的Unique Paths 和Unique Paths II一样。

Unique Paths

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 thr grid(marked ‘Finish’ in the diagram below).

How many possible unique paths are there?

NOTE: m and n will be at most 100.

Unique Paths II

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 3*3 grid as il本文来源gao($daima.com搞@代@#码(网5lustrated below.

[  [0,0,0],  [0,1,0],  [0,0,0]]

The total number of Unique paths is 2.

NOTE: m and n will be at most 100.

解法:

Unique Paths

public int uniquePaths(int m, int n) {        //这里用了DP解法,因为这种解法可以最大程度避免整数越界问题        int[][] memo = new int[m][n];        for(int i=0; i<m; i++)            memo[i][0] = 1;        for(int i=0; i<n; i++)            memo[0][i] = 1;                for(int i=1; i<m; i++)            for(int j=1; j<n; j++)                memo[i][j] = memo[i-1][j] + memo[i][j-1];                return memo[m-1][n-1];    }

Unique Paths II

这里用了一维数组来代替二维数组

public int uniquePathsWithObstacles(int[][] obstacleGrid) {        int m = obstacleGrid.length;        if(m == 0) return 0;        int n = obstacleGrid[0].length;        if(obstacleGrid[0][0] == 1) return 0;        int[] table = new int[n];        table[0] = 1;        for(int i=0; i<m; i++){            for(int j=0; j0)                    table[j] = table[j-1] + table[j];            }        }        return table[n-1];    }

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:CCI 9.2 机器人移动路径

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址