HDU1241 Oil Deposits

来源:互联网 发布:数据营销有什么书 编辑:程序博客网 时间:2024/05/17 02:26

求连通块,我用的BFS


#include<iostream>#include<cstdio>#include<cstring>#include<stack>#include<queue>using namespace std;struct Node{    int y, x;    Node ( int yy = 0, int xx = 0 ) : y ( yy ), x ( xx ) {}} t;const int N = 110,dir[8][2]={1,0,-1,0,0,1,0,-1,1,1,1,-1,-1,1,-1,-1};int n, m,res;char maze[N][N];bool vis[N][N];void bfs(){    memset ( vis, 0, sizeof ( vis ) );     res=0;    for ( int i = 0; i < n; i++ )        for ( int j = 0; j < m; j++ )            if ( maze[i][j] == '@' && vis[i][j] == 0 )            {                res++;                vis[i][j]=1;                queue<Node> q;                q.push ( Node ( i, j ) );                while ( !q.empty() )                {                    t = q.front();                    q.pop();                    for(int k=0;k<8;k++)                    {                        int ny=t.y+dir[k][0];                        int nx=t.x+dir[k][1];                        if(ny>=0&&ny<n&&nx>=0&&nx<m&&vis[ny][nx]==0&&maze[ny][nx]=='@')                            {                                vis[ny][nx]=1;                                q.push(Node(ny,nx));                            }                    }                }            }}int main(){    //freopen("in.txt","r",stdin);    while ( scanf ( "%d%d", &n, &m ) != EOF )    {        if(n==0)            break;        getchar();        for ( int i = 0; i < n; i++ )            scanf("%s",maze[i]);        bfs();        printf("%d\n",res);    }    return 0 ;}


0 0
原创粉丝点击