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 ,就dfs 吃掉他的邻居。

     1 class Solution {
     2 public:
     3     int numIslands(vector<vector<char>>& grid) {
     4         if(grid.size()==0) return 0;
     5         int cnt =0;
     6         for(int i =0;i<grid.size();i++)
     7             for(int j = 0;j <grid[0].size();j++){
     8                 cnt+=grid[i][j]-'0';
     9                 dfs(grid,i,j);
    10             }
    11         return cnt;   
    12     }
    13     void dfs(vector<vector<char>>& grid,int x,int y ){
    14         if(x>= grid.size()||y>=grid[0].size()||x<0||y<0||grid[x][y]=='0') return ;
    15         grid[x][y] = '0';
    16         dfs( grid,x-1,y);
    17         dfs( grid,x+1,y);
    18         dfs( grid,x,y-1);
    19         dfs( grid,x,y+1);
    20     }
    21 };

    http://zxi.mytechroad.com/blog/searching/leetcode-200-number-of-islands/

    
    
  • 相关阅读:
    编码
    浏览器翻页
    验证码识别
    时间
    phantomjs配置
    产品
    java范型的理解
    使用JDBC连接数据库
    垃圾回收机制
    java的内存区域 && java内存模型
  • 原文地址:https://www.cnblogs.com/zle1992/p/10289487.html
Copyright © 2011-2022 走看看