[Lintcode] Unique Paths I,II

本文深入探讨了独特的路径问题,从基本的二维网格路径算法出发,逐步引入墙的概念,详细阐述了一维滚动数组实现的独特路径计算方法,并通过实例演示了如何解决包含障碍物的路径问题。

Unique Paths I


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

How many possible unique paths are there?

一维滚动数组实现。

public class Solution {
    /**
     * @param n, m: positive integer (1 <= n ,m <= 100)
     * @return an integer
     */
    public int uniquePaths(int m, int n) {
        int[] res = new int[n];
        for(int i = 0; i < n; i++) res[i] = 1;
        
        for(int i = 1; i < m; i++) {
            for(int j = 1; j < n; j++) {
                res[j] += res[j - 1];
            }
        }
        return res[n - 1];
    }
}

Unique Paths II 
加入墙,此时考虑两种情况,墙在最左侧时,墙在中间时。
在最左侧时,要初始化一维数组的首元素为0。在最上恻时,不用考虑,因为迭代时是从左向右迭代,当遇到1时,保留i-1的路径数量即可。但是在左侧时,每次重新开始时都会魔人存在一条路径。

public class Solution {
    /**
     * @param obstacleGrid: A list of lists of integers
     * @return: An integer
     */
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int height = obstacleGrid.length;
        if(height == 0) return 0;
        int width = obstacleGrid[0].length;
        int[] res = new int[width];
        if(height == 1 && width == 1 && obstacleGrid[0][0] == 0) return 1;
        
        for(int i = 0; i < width; i++) {
            if(obstacleGrid[0][i] != 1){
                res[i] = 1;
            }
            else {
                break;
            }
        }
        
        for(int i = 1; i < height; i++) {
            if(obstacleGrid[i][0] == 1) res[0] = 0;
            for(int j = 1; j < width; j++) {
                if(obstacleGrid[i-1][j] != 1 && obstacleGrid[i][j-1] != 1)
                    res[j] += res[j - 1];
                else if(obstacleGrid[i-1][j] == 1 && obstacleGrid[i][j-1] == 1)
                    res[j] = 0;
                else if(obstacleGrid[i-1][j] == 1)
                    res[j] = res[j-1];
                else if(obstacleGrid[i][j-1] == 1)
                    res[j] = res[j];
            }
        }
        
        return obstacleGrid[height - 1][width - 1] == 1 ? 0 : res[width - 1];
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值