簡體   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