-1

Here is a peice of code i am trying to run:

public int numIslands(char[][] grid) {
    if(grid==null)
        return 0;
    else
    {
        int count=0;
        gridtemp=grid; // gridtemp is a global character array
        visited=new boolean[grid.length][grid[0].length]; //****ERROR******
        for(int i=0;i<grid.length;i++)
        {
            for(int j=0;j<grid[0].length;j++)
            {
                if(IslandCount(i,j)>1)
                    count++;
            }
        }
        System.out.println(count);
        return count;
    }
}

This code is throwing error java.lang.ArrayIndexOutOfBoundsException: 0 as indicated above in code snippet

Magnum
  • 83
  • 1
  • 5
  • 4
    Even `grid` is not `null`, it can be empty, i.e., `grid.length == 0`. In that case, `grid[0]` will throw `ArrayIndexOutOfBoundsException`. – Alex Oct 19 '17 at 04:29
  • Add the definition of visited – c0der Oct 19 '17 at 04:30
  • 1
    The issue is that when `grid` is empty, there's no such thing as `grid[0]`. Empty and null aren't the same thing. (In other words, Alex is right, but types faster than I do. Dave has given you a red herring). – Dawood ibn Kareem Oct 19 '17 at 04:30
  • Have you declared `char visited[][]` ? – Karan Oct 19 '17 at 04:33

2 Answers2

0

The array with a length 0 doesn't have to be null.

@Test
public void testArrayWithLengthZero(){
    int[] i = new int[0];
    System.out.println(i==null);
}

The output is false.

0

There could be 2 issues in your code

  • Looks like grid[0] is null. Put a check for grid[0].
  • grid might be of length 0, so when you are accessing grid[0] it throws ArrayIndexOutOfBoundsException
nagendra547
  • 5,672
  • 3
  • 29
  • 43