I'm writing a Java program to solve the following problem statement:
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
I went through the algorithm to implement which is essentially using DFS to compute the number of connected components.
The following is the code that I've written:
public class Solution {
public int numIslands(char[][] grid) {
boolean [][] visited = new boolean [grid.length][grid[0].length];
int numClusters = 0;
for(int i=0; i<visited.length; i++)
{ for(int j=0; j<visited[0].length; j++)
visited[i][j] = false;
}
for(int i=0; i<visited.length; i++)
{ for(int j=0; j<visited[0].length; j++)
{ if(grid[i][j] == '0')
{ visited[i][j] = true;
continue;
}
if(!visited[i][j])
{
DFS(grid,i,j,visited);
numClusters++;
}
}
}
return numClusters;
}
public void DFS(char[][] grid, int i, int j, boolean[][] visited)
{
if(i > grid.length || j > grid[0].length || i < 0 || j < 0)
return;
if(visited[i][j]) // Line where the error is thrown.
return;
visited[i][j] = true;
if(grid[i][j] == '0')
return;
DFS(grid,i+1,j,visited);
DFS(grid,i-1,j,visited);
DFS(grid,i,j+1,visited);
DFS(grid,i,j-1,visited);
}
}
I'm getting an ArrayIndexOutOfBoundsException when I try to execute this for the input
["11000","11000","00100","00011"]
The error is on the line - if(visited[i][j]) of the DFS function definition. I've updated it in the code as well as a comment.
Any help on this would be great!