user15346585
user15346585

Reputation:

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

The nextint part is the problem but couldn't be fixed. it was supposed to show float output for the uniquePaths_With_obstacle_Grid, but couldn't be solved by int at least :)

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

Upvotes: 0

Views: 27

Answers (1)

Gautham M
Gautham M

Reputation: 4935

s.nextInt() just gets a single input, which could only be set to an int, but you are trying to initialize an int[][] with an int data.

To fix this you need to take the input in a loop:

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();
    }
}

Upvotes: 1

Related Questions