[Leetcode] 200. Number of Islands

  1. 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:
11110110101100000000
Answer: 1
Example 2:
11000110000010000011
Answer: 3
Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.

public class Solution {
    public int numIslands(char[][] grid) {
        if(grid.length == 0 || grid[0].length == 0) return 0;
        int sum = 0;
        for(int i = 0; i < grid.length; i++)
            for(int j = 0; j < grid[0].length; j++)
                sum += dfs(grid,i,j);
        return sum;
    }
    private int dfs(char[][] grid, int i, int j){
        if(grid[i][j] == '0') return 0;
        grid[i][j] = '0';
        int[][] dir = {{0,-1} , {0,1} ,{-1,0} ,{1,0}};
        for(int m = 0; m < dir.length; m++){
            int x = i+dir[m][0], y = j+dir[m][1];
            if(x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && grid[x][y] == '1')
            dfs(grid,x,y);
        }
        return 1;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容