zoukankan      html  css  js  c++  java
  • hdu 1241 dfs

    题意:给两个整数n、m,接下来输入m行n列的一张图,如果m==0停止输入,否则 1 <= m <= 100 and 1 <= n <= 100,八方向联通,求‘@’组成的不联通的块数。

    样例:

    这应该是学dfs的模版题,挑战程序设计竞赛上有类似的题目,这道题稍微有点不同的就是是八方向联通而已,算法的思想还是一模一样,找到一个‘@’,然后开始按八方向递归搜索,将搜到的‘@’都改为‘*’,直到最后所有的都变为了‘*’,搜索也就结束了。

    #include<iostream>
    #include<math.h>
    #include<algorithm>
    #include<stdio.h>
    #include<string.h>
    #include<string>
    #define ll long long
    #define MAX_N 105
    
    using namespace std;
    
    int n,m;
    char pi[MAX_N][MAX_N];
    int dir[8][2] = {{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};  //八方向
    int ans;
    
    bool judge(int x,int y)
    {
        if(x<1 || x>m || y<1 || y>n)
            return false;
        return true;
    }
    void dfs(int x,int y)
    {
        for(int i = 0; i < 8; i++)
        {
            int xx = x+dir[i][0];
            int yy = y+dir[i][1];
            if(judge(xx,yy) && pi[xx][yy]=='@')
            {
                pi[xx][yy] = '*';  //将搜到的‘@’改为‘*’
                dfs(xx,yy);
            }
        }
    }
    void solve()
    {
        ans = 0;
        for(int i = 1; i <= m; i++)
        {
            for(int j = 1; j <= n; j++)
            {
                if(pi[i][j]=='@')
                {
                    pi[i][j] = '*';
                    dfs(i,j);
                    ans++;
                }
            }
        }
    }
    int main()
    {
        while(cin>>m>>n,m)
        {
            for(int i = 1; i <= m; i++)
            {
                for(int j = 1; j <= n; j++)
                {
                    cin>>pi[i][j];
                }
            }
            solve();
            cout<<ans<<endl;
        }
        return 0;
    }
    
  • 相关阅读:
    洛谷P3003 [USACO10DEC]苹果交货Apple Delivery
    洛谷P1576 最小花费
    洛谷P1821 [USACO07FEB]银牛派对Silver Cow Party
    洛谷P1948 [USACO08JAN]电话线Telephone Lines
    洛谷P3371【模板】单源最短路径
    洛谷P2384最短路
    FirstOfAll
    Proxy模式:管理第三方API
    Abstract Server模式,Adapter模式和Bridge模式
    Observer模式
  • 原文地址:https://www.cnblogs.com/Xycdada/p/8005345.html
Copyright © 2011-2022 走看看