[LeetCode.200]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:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

代碼實現

public class NumberOfIslands {
    public static int numIslands(char[][] grid) {
        int sum = 0;
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid[0].length; j++){
                if(grid[i][j] == '1'){
                    sum++;
                    dfs(grid,i,j);
                }
            }
        }
        return sum;
    }
    public static void dfs(char[][] grid,int i,int j){
        if(i >= 0 && i < grid.length && j >= 0 && j < grid[0].length){
            if(grid[i][j] == '1'){
                grid[i][j] = '0';
                dfs(grid,i - 1,j);
                dfs(grid,i,j - 1);
                dfs(grid,i + 1,j);
                dfs(grid,i,j + 1);
            }
        }
    }
    public static void main(String[] args){
        char[][] grid = {
                {'1','1','0','0','0'},
                {'1','1','0','0','0'},
                {'0','0','1','0','0'},
                {'0','0','0','1','1'}};
        System.out.println(numIslands(grid));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章