zoukankan      html  css  js  c++  java
  • 【连通区域个数】

    #include <iostream>
    using namespace std;
    void DFS(int R,int W,int i, int j,int **visited,int **mVexs)
    {
        int r,w;
        visited[i][j] = 1;    //将该位置的访问标签置为1
        // 遍历该顶点的所有邻接顶点。若是没有访问过且元素为1,则继续深度访问
        if(j>=1)
        {
            r = i;w = j-1;
            {
                if (!visited[r][w] && mVexs[r][w])
                    DFS(R,W,r,w, visited,mVexs);
            }
        }
        if(j<W-1)
        {
            r = i;w = j+1;
            {
                if (!visited[r][w] && mVexs[r][w])
                    DFS(R,W,r,w, visited,mVexs);
            }
        }
        if(i>=1)
        {
            r = i-1;w = j;
            {
                if (!visited[r][w] && mVexs[r][w])
                    DFS(R,W,r,w, visited,mVexs);
            }
        }
        if(i<R-1)
        {
            r = i+1;w = j;
            {
                if (!visited[r][w] && mVexs[r][w])
                    DFS(R,W,r,w, visited,mVexs);
            }
        }
    }
    void countSun(int R,int W,int **mVexs) {
        int **visited=new int*[R];
        int i,j;
        for(i=0;i<R;i++)
            visited[i]=new int[W];
        for(i=0;i<R;i++)
            for(j = 0;j<W;j++)
                visited[i][j] = 0;    //定义访问标记数组,初始化为1,一旦相应位置的元素被访问,则将其置为0
    
        int count = 0;     //连通区域的个数
        cout<<"DFS"<<endl;
         for (i = 0; i < R; i++)
        {
            for(j = 0;j<W;j++)
            {
                if (!visited[i][j] && mVexs[i][j])   //依次访问目前尚未被访问,且元素为1的位置
                {
                    DFS(R,W,i,j,visited,mVexs);     //访问该位置以及其邻域位置
                    count++;       //连通区域个数+1
                }
            }
         }
        cout <<count<< endl;
    }
    int main() {
        int res=0;
        int R=0;
        int W=0;
        cout<<"请输入R:";
        cin>>R;
        cout<<"请输入W:";
        cin>>W;
        int i,j;
        int **arr=new int*[R];
        for(i=0;i<R;i++)
            arr[i]=new int[W];
        for(i=0;i<R;i++)
            for(int j=0;j<W;j++)
                cin>>arr[i][j];
        for(i=0;i<R;i++)
        {
            for(j=0;j<W;j++)
                cout<<arr[i][j]<<' ';
            cout<<endl;
        }
        countSun(R,W,arr);    
        return 0;
    }
  • 相关阅读:
    Swagger注解及参数细节的正确书写。
    TCP连接为什么三次握手四次挥手
    OpenMeetings安装
    [LeetCode]Best Time to Buy and Sell Stock III
    [LeetCode]Best Time to Buy and Sell Stock
    [LeetCode]Best Time to Buy and Sell Stock II
    [LeetCode]Delete Node in a Linked List
    [LeetCode]Lowest Common Ancestor of a Binary Search Tree
    [LeetCode]Invert Binary Tree
    [LeetCode]Same Tree
  • 原文地址:https://www.cnblogs.com/EstherLjy/p/9392279.html
Copyright © 2011-2022 走看看