ZOJ 2412 Farm Irrigation

转载请注明出处:http://blog.csdn.net/a1dark

分析:蛋蛋疼、跟上一题一样、图的DFS遍历、不过这里需要预处理一下字符、然后再DFS、

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
char mp[55][55];
int used[55][55];
int N,m,sum;
struct node{
    int up,down,left,right;
};
node n[11]={{1,0,1,0},{1,0,0,1},{0,1,1,0},{0,1,0,1},{1,1,0,0},{0,0,1,1},{1,0,1,1},{1,1,1,0},{0,1,1,1},{1,1,0,1},{1,1,1,1}};    //保存农田形状
int getnode(char x){
    return x-'A';
}
int cango(int x,int y){
    if(x<=0||x>m||y<=0||y>N)
        return 0;
    return 1;
}
void dfs(int x,int y){
    int i,j,k,xx,yy;
   for(i=0;i<4;i++){
       if(i==0){   //上走
           xx=x-1;
           yy=y;
           if(cango(xx,yy)&&!used[xx][yy]&&n[getnode(mp[xx][yy])].down&&n[getnode(mp[x][y])].up){
               used[xx][yy]=1;
               dfs(xx,yy);
           }
        }
       else if(i==1){
           xx=x+1;
           yy=y;
        if(cango(xx,yy)&&!used[xx][yy]&&n[getnode(mp[xx][yy])].up&&n[getnode(mp[x][y])].down){
               used[xx][yy]=1;
               dfs(xx,yy);
           }
       }
      else if(i==2){
           xx=x;
           yy=y-1;
        if(cango(xx,yy)&&!used[xx][yy]&&n[getnode(mp[xx][yy])].right&&n[getnode(mp[x][y])].left){
               used[xx][yy]=1;
               dfs(xx,yy);
           }
       }
     else if(i==3){
           xx=x;
           yy=y+1;
        if(cango(xx,yy)&&!used[xx][yy]&&n[getnode(mp[xx][yy])].left&&n[getnode(mp[x][y])].right){
               used[xx][yy]=1;
               dfs(xx,yy);
           }
       }
   }
}
int main(){
    int i,j,k;
    while(scanf("%d%d",&m,&N)&&N!=-1&&m!=-1){
        sum=0;
        memset(used,0,sizeof(used));
        for(i=1;i<=m;i++)
          for(j=1;j<=N;j++){
              scanf("%1s",&mp[i][j]);
          }
       for(i=1;i<=m;i++)
            for(j=1;j<=N;j++){
                if(used[i][j]==0){
                    sum++;
                    dfs(i,j);
                }
           }
       cout<<sum<<endl;
    }
    return 0;
}


你可能感兴趣的:(ACM,图论,DFS遍历)