Number of Islands

重点题目

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.

Example 1:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

Complexity Analysis

  • Time complexity : O(M×N) where M is the number of rows and N is the number of columns.

  • Space complexity : O(min(M,N)) because in worst case where the grid is filled with lands, the size of queue can grow up to min(MN).

class Solution {
    public int numIslands(char[][] grid) {
        //BFS
        if(grid == null || grid.length == 0 || grid[0].length == 0)
            return 0;
        
        int res = 0;
        
        boolean[][] visited = new boolean[grid.length][grid[0].length];
        
        for(int i = 0; i < grid.length;i++){
            for(int j = 0; j < grid[0].length;j++){
                if(grid[i][j] == '1' && !visited[i][j]){
                    res++;
                    bfs(grid,visited,i,j);
                }
            }
        }
        
        
        return res;
    }
    
    public void bfs(char[][] grid,boolean[][] visited, int x,int y){
        int[] dx = {1,0,-1,0};
        int[] dy = {0,1,0,-1};
        
        Queue<Integer> xQueue = new LinkedList<>();
        Queue<Integer> yQueue = new LinkedList<>();
        
        xQueue.offer(x);
        yQueue.offer(y);
        
        while(!xQueue.isEmpty()){

            int X = xQueue.poll(), Y = yQueue.poll();
            
            for(int i = 0; i < 4;i++){
                
                
                int cx = X+ dx[i];
                int cy = Y + dy[i];
                
                if(inBound(grid, cx,cy) && grid[cx][cy] == '1' && !visited[cx][cy]){
                    visited[cx][cy] = true;
                    xQueue.offer(cx);
                    yQueue.offer(cy);
                }
            }
        }
        
    }
    
    public boolean inBound(char[][] grid, int x, int y){
        return x >=0 && x < grid.length && y >=0 && y < grid[0].length;
    }
}

Last updated