zoukankan      html  css  js  c++  java
  • 200. Number of Islands(DFS)

    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




     1 class Solution {
     2     public int numIslands(char[][] grid) {
     3         if(grid==null) return 0;
     4         int cnt =0;
     5         for(int i =0;i<grid.length;i++){
     6             for(int j =0;j<grid[0].length;j++){
     7                 if(grid[i][j]=='1'){
     8                     dfs(grid,i,j);
     9                     cnt++;
    10                 }
    11             }
    12         }
    13         return cnt;
    14     }
    15     private void dfs(char[][] grid,int i,int j){
    16         if(i<0||j<0||i>=grid.length||j>=grid[0].length||grid[i][j]=='0') return ;
    17         grid[i][j] = '0';
    18         dfs(grid,i-1,j);
    19         dfs(grid,i+1,j);
    20         dfs(grid,i,j+1);
    21         dfs(grid,i,j-1);
    22     }
    23     
    24 }
  • 相关阅读:
    UILabel 详解
    didMoveToSuperView 引发的思考
    Source
    设计模式
    Code ReView
    UIApearance
    UINavigationBar
    initWithNibName与viewDidLoad的执行关系以及顺序
    bLock 回调 就是这么简单!
    程序语言小记
  • 原文地址:https://www.cnblogs.com/zle1992/p/9166906.html
Copyright © 2011-2022 走看看