1. 程式人生 > >LeetCode刷題Medium篇Number of Islands

LeetCode刷題Medium篇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

十分鐘嘗試

沒有思路,學習了一下一個DFS思路,簡單整理一下:

1. 掃描二維矩陣,如果當前元素是1,island數目加1,然後遞迴遍歷當前元素的上,下,左,右,四個方位的元素

2. 遞迴遍歷上下左右元素,如果元素是1,設定為2,防止遞迴過程中重複,繼續遞迴,出口條件為超越邊界

寫一下程式碼試試:

class Solution {
    
    //把所有相連的1都設定為2,不計入island 數目
    private void dFs(char[][] grid,int i ,int j){
        if(i<0||j<0||i>grid.length-1||j>grid[0].length-1){
            return;
        }
        if(grid[i][j]=='1'){
            grid[i][j]=2;
            dFs(grid,i,j+1);
            dFs(grid,i,j-1);
            dFs(grid,i+1,j);
            dFs(grid,i-1,j);
        }
        
    }
    
    
    public int numIslands(char[][] grid) {
        if(grid==null||grid.length==0||grid[0].length==0){
            return 0;
        }
        int count=0;
        for(int i=0;i<grid.length;i++){
            for(int j=0;j<grid[i].length;j++){
                if(grid[i][j]=='1'){
                    count++;
                    dFs(grid,i,j);
                }
                
            }
            
        }
        return count;
        
    }
}