Domanda

I have written the following code for finding the number of possible paths in a rat in a maze problem, but it s showing NullPointer Exception at lines 23 and 29 shown in bold. Please help.

import java.util.*;
import java.io.*;
public class rat_in_a_maze

{

    static int n;
    static int[][] a;
    static int path;

    public static void main(String[] ar) throws IOException
    {
        n=7;
        int a[][]={ {0,0,1,0,0,1,0},
                    {1,0,1,1,0,0,0},
                    {0,0,0,0,1,0,1},
                    {1,0,1,0,0,0,0},
                    {1,0,1,1,0,1,0},
                    {1,0,0,0,0,1,0},
                    {1,1,1,1,0,0,0}};

        search(0,0); //NPE here
        System.out.println(path);
    }

    public static void search(int i, int j)
    {
        if(!exist(i,j) || a[i][j] == 1) // NPE here
            return;
        if(i == n-1 && j == n-1)
        {
            path++;
            return;
        }
        a[i][j] = 1;
        search(i+1,j);
        search(i-1,j);
        search(i,j+1);
        search(i,j-1);
        a[i][j] = 0;
    }

    public static boolean exist(int i, int j)
    {
        return i>=0 && j >=0 && i < n && j < n;
    }
}
È stato utile?

Soluzione

Your two-dimensional array a is null. Your intention is to initialize it inside the main() method, but you declare new local array instead of initializing the global static array a.
Your code should be like this:

public static void main(String[] ar) throws IOException {
    n=7;
    a = new int[][]{ {0,0,1,0,0,1,0},
                {1,0,1,1,0,0,0},
                {0,0,0,0,1,0,1},
                {1,0,1,0,0,0,0},
                {1,0,1,1,0,1,0},
                {1,0,0,0,0,1,0},
                {1,1,1,1,0,0,0}};

    search(0,0);
    System.out.println(path);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top