zoukankan      html  css  js  c++  java
  • leetcode 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:

    11110
    11010
    11000
    00000

    Answer: 1

    Example 2:

    11000
    11000
    00100
    00011

    Answer: 3

    简单的DFS求联通块。

    class Solution {
    public:
        void dfs(int x,int y,vector<vector<char> >& g){
            used[x][y]=1;
            for(int i=0;i<4;i++){
                int tx=x+dx[i];
                int ty=y+dy[i];
                if(tx>=0&&tx<n&&ty>=0&&ty<m&&used[tx][ty]==0&&g[tx][ty]=='1'){
                    dfs(tx,ty,g);
                }
            }
            return;
        }
        int numIslands(vector<vector<char> >& grid) {
            n = grid.size();
            if(n==0) return 0;
            m = grid[0].size();
            used = vector<vector<int> >(n,vector<int>(m,0));
            int ans=0;
            
            for(int i=0;i<n;i++){
                for(int j=0;j<m;j++){
                    if(used[i][j]==0&&grid[i][j]=='1'){
                        dfs(i,j,grid);
                        ans++;
                    }
                }
            }
            return ans;
        }
        
    private:
        int n,m;
        int dx[4]={0,0,1,-1};
        int dy[4]={1,-1,0,0};
        vector<vector<int> >used;
    };
  • 相关阅读:
    网络编程
    并发编程-线程池
    并发编程-集合
    并发编程-AQS
    并发编程-CAS
    并发编程-volatile和synchronized的区别
    并发编程-synchronized
    并发编程-java内存模型
    JVM-分代垃圾回收器
    性能优化
  • 原文地址:https://www.cnblogs.com/zywscq/p/5429124.html
Copyright © 2011-2022 走看看