繁体   English   中英

通过获取输入从网格的左上角到右下角的唯一路径

[英]Unique paths from top-left corner to bottom-right corner of grid by getting input

import java.util.*;
public class ans {
    public static int uniquePaths_With_obstacle_Grid(int[][] obstacle_Grid) {
        int m = obstacle_Grid.length;
        if (m <= 0) {
            return 0;
        }
        int n = obstacle_Grid[0].length;
        if (n <= 0) {
            return 0;
        }
        int[][] dp = new int[m + 1][n + 1];
        dp[m][n - 1] = 1;
        for (int i = m - 1; i >= 0; --i) {
            for (int j = n - 1; j >= 0; --j) {
                dp[i][j] = (obstacle_Grid[i][j] == 0) ? dp[i + 1][j] + dp[i][j + 1] : 0;
            }
        }
        return dp[0][0];
    }
}

nextint 部分是问题,但无法修复。 它应该为 uniquePaths_With_obstacle_Grid 显示 float output,但至少不能通过 int 解决:)

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    int[][] obstacle_Grid = s.nextInt();
    System.out.println("Unique paths from top-left corner to bottom-right corner of the said grid (considering some obstacles): "+uniquePaths_With_obstacle_Grid(obstacle_Grid));
}       

s.nextInt()只获得一个输入,它只能设置为int ,但您正在尝试使用int数据初始化int[][]

要解决此问题,您需要循环输入:

Scanner s = new Scanner(System.in);
int m = s.nextInt(); // row size
int n = s.nextInt(); // column size
int[][] obstacle_Grid = new int[m][n];
for(int i=0;i<m;i++) {
    for(int j=0;j<n;j++) {
        obstacle_Grid[i][j] = s.nextInt();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM