200. Number of Islands

Medium
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
Solution:
If a cell with value 1 and is not visited yet, new island is found. visit all adjacent cell 1 in this island(dfs), increase the count.
dfs: 
if the current cell is out the range of the matrix, return;
if current cell with value 1 and not visited yet, mark visited matrix value to true and visit all adjacent cell.

class Solution {
    public int numIslands(char[][] grid) {
        if(grid == null || grid.length == 0) return 0;
        int n = grid.length;
        int m = grid[0].length;
        int count = 0;
        boolean[][] used = new boolean[n][m];
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(grid[i][j] == '1' && !used[i][j]){
                    dfs(grid,i,j,used);
                    count++;
                }
            }
        }
        return count;
    }
    public void dfs(char[][] grid, int i, int j, boolean[][] used){
        if(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) return;
        if(grid[i][j] == '1' && !used[i][j]){
            used[i][j] = true;
            dfs(grid,i+1,j,used);
            dfs(grid,i,j+1,used);
            dfs(grid,i-1,j,used);
            dfs(grid,i,j-1,used);
        }
    }
}



Comments

Popular posts from this blog

MockInterview:785. Is Graph Bipartite?

geeksforgeeks:findFind zeroes to be flipped so that number of consecutive 1’s is maximized

94.Binary Tree Inorder Traversal