Skip to main content

Number of Islands

Level - Medium

Statement:

Given an m x n 2D binary grid which represents a map of '1's (land) and '0's (water), return 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.

Example 1

example1

Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3

Example 2

Input: grid = [
["1","1"],
["1","0"],
["1","0"],
["0","0"]
]
Output: 1

Algorithm

  1. Initialize a queue<int[]> to store the co-ordinates(x,y) of the elements in the grid and a visited array to keep track of the visited elements.
  2. Loop through all the elements in the grid.
  3. If the element is 1(land) and has not been visited before, increment the count of islands and perform BFS on that element.
  4. To perform BFS on an element:
    • Initialize the queue with the starting co-ordinate(0,0) and mark it as visited by setting visited[x][y] = true.
    • Loop through the following steps until the queue is empty:
      • Poll the co-ordinate from the queue.
      • Move in all four directions (up, down, left, and right) and if an element in any direction is 1 and has not been visited, put that co-ordinate in the queue and mark it as visited.
    • After the BFS is complete, we will have visited all the elements in the island. We will continue to loop through the grid and perform BFS on any unvisited 1(land) elements until we have found all the islands.
  5. Return the count of islands

Code

 public void bfs(int x,int y,char[][] grid,boolean[][] visited,int n,int m){
Queue<int[]> q = new LinkedList<>();
int[] dx = {0,0,-1,1};
int[] dy = {-1,1,0,0};

// init the queue
q.add(new int[]{x,y});visited[x][y] = true;
while(!q.isEmpty()){
int[] point = q.poll();
// go to all the directions
for(int i=0;i<4;i++){
int new_x = dx[i]+point[0],new_y = dy[i]+point[1];
if(new_x>=0 && new_x<n && new_y>=0 && new_y<m && grid[new_x][new_y]=='1' && !visited[new_x][new_y]){
q.add(new int[]{new_x,new_y});
visited[new_x][new_y] = true;
}
}
}
return;
}
public int numIslands(char[][] grid) {
int n = grid.length;
int m = grid[0].length;
// track visited to avoid infinite loop
boolean[][] visited = new boolean[n][m];
int count = 0;

for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(grid[i][j]=='1' && !visited[i][j]){
count++;
bfs(i,j,grid,visited,n,m);
}
}
}

return count;
}

Complexity

Time Complexity:

O(N*N))

Space Complexity:

O(N*N)