Skip to content
This repository was archived by the owner on Aug 14, 2024. It is now read-only.

Latest commit

 

History

History
68 lines (52 loc) · 1.37 KB

200.md

File metadata and controls

68 lines (52 loc) · 1.37 KB

200. Number of Islands

Description

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:*

11110
11010
11000
00000

Answer: 1

*Example 2:*

11000
11000
00100
00011

Answer: 3

Thinking Process

  1. Taverse the array, whenever see land, do a BFS from that tile, flip it to water

Code

public class Solution {
    int[][] dirs = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
    public int numIslands(char[][] grid) {
        int count = 0;
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid[0].length; j++){
                if(grid[i][j] == '1'){
                    bfs(grid, i, j);
                    count++;
                }
            }
        }
        
        return count;
    }
    
    void bfs(char[][] grid, int i, int j){
        grid[i][j] = '0';
        for(int[] dir:dirs){
            int x = i + dir[0];
            int y = j + dir[1];
            if(x >= 0 && y >= 0 && x < grid.length && y < grid[0].length && grid[x][y] == '1'){
                bfs(grid, x, y);
            }
        }
        return;
    }   
}

Complexity

  1. O(mn) time complexity, O(1) space complexity