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


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];
}
}

下一个部分是问题,但无法修复。它应该为uniquePaths_With_obstacle_Grid显示浮点输出,但至少不能通过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();
}
}

最新更新