CCI 9.2 机器人移动路径

php中文网
发布: 2016-06-07 15:43:17
原创
1424人浏览过

摄像有个机器人坐在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?

CCI 9.2 机器人移动路径

NOTE: m and n will be at most 100.

Unique Paths II

Follow up for "Unique Paths".

Codeium
Codeium

一个免费的AI代码自动完成和搜索工具

Codeium 228
查看详情 Codeium

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 illustrated 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; j<n; j++){
                if(obstacleGrid[i][j] == 1)
                    table[j] = 0;
                else if(j>0)
                    table[j] = table[j-1] + table[j];
            }
        }
        return table[n-1];
    }
登录后复制


最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号