Robot in a Grid: java 走地牙 CTCI 8.2

Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns.The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right.

 

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章