标签:
这题可以dfs也可以并查集,感觉并查集比较简单就用并查集做了,题目的数据量是有误的,n,m应该远大于50;
#include<iostream> #define maxn 500+5 using namespace std; int n,m; int dir[11][4]={{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}}; char mapp[maxn][maxn]; int f[maxn*maxn]; int dfs(int x) { if(f[x]!=x) f[x]=dfs(f[x]); return f[x]; } void build(int x,int y) { if(dfs(x)!=dfs(y)) { f[dfs(x)]=dfs(y); } } int main() { while(cin>>n>>m) { if(n==-1&&m==-1) break; for(int i=0;i<n;i++) cin>>mapp[i]; for(int i=0;i<n*m;i++) f[i]=i; for(int i=0;i<n*m;i++) { int x=i/m; int y=i%m; if(y!=m-1&&dir[mapp[x][y]-'A'][3]&&dir[mapp[x][y+1]-'A'][2]) build(i,i+1); if(x!=n-1&&dir[mapp[x][y]-'A'][1]&&dir[mapp[x+1][y]-'A'][0]) build(i,i+m); } int sum=0; for(int i=0;i<n*m;i++) { if(f[i]==i) sum++; } cout<<sum<<endl; } return 0; }
标签:
原文地址:http://blog.csdn.net/zafkiel_nightmare/article/details/45920875