标签:dfs bfs algorithm map struct
2 3 4 1 0 0 0 0 0 1 1 1 1 1 0 5 5 1 1 1 1 0 0 0 1 0 1 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1
2 3
DFS:
#include<cstdio> #include<cstring> #define N 200 #define M 200 int map[N][M] = {0}; void DFS(int i,int j) { if(map[i][j-1]) { map[i][j-1]=0; DFS(i,j-1); } if(map[i][j+1]) { map[i][j+1]=0; DFS(i,j+1); } if(map[i-1][j]) { map[i-1][j]=0; DFS(i-1,j); } if(map[i+1][j]) { map[i+1][j]=0; DFS(i+1,j); } } int main() { int t,n,m; int i,j,count; scanf("%d",&t); while(t--) { scanf("%d %d",&n,&m); count=0; for(i=1;i<=n;i++) for(j=1;j<=m;j++) scanf("%d",&map[i][j]); for(i=1;i<=n;i++) for(j=1;j<=m;j++) if(map[i][j]) { count++; map[i][j]=0; DFS(i,j); } printf("%d\n",count); } return 0; }再看这个:#include<cstdio> #include<cstring> #define N 200 #define M 200 int map[N][M] = {0}; int f[4][2]={{-1,0},{1,0},{0,1},{0,-1}}; void DFS(int i,int j) { int k; map[i][j]=0; for(k=0;k<4;k++) { if(map[i+f[k][0]][j+f[k][1]]==1) DFS(i+f[k][0],j+f[k][1]); } } int main() { int t,n,m; int i,j,count; scanf("%d",&t); while(t--) { scanf("%d %d",&n,&m); count=0; for(i=1;i<=n;i++) for(j=1;j<=m;j++) scanf("%d",&map[i][j]); for(i=1;i<=n;i++) for(j=1;j<=m;j++) if(map[i][j]) { count++; map[i][j]=0; DFS(i,j); } printf("%d\n",count); } return 0; }BFS:#include<cstdio> #include<cstring> #include<algorithm> #include<queue> #define N 200 #define M 200 using namespace std; int map[N][M] = {0}; int f[4][2]={{-1,0},{1,0},{0,1},{0,-1}}; struct pool { int a,b; }; queue<pool> v; void BFS(int i,int j) { int k; pool p,x,y; p.a=i; p.b=j; v.push(p); map[i][j]=0; while(!v.empty()) { x=v.front(); for(k=0;k<4;k++) { if(map[x.a+f[k][0]][x.b+f[k][1]]) { map[x.a+f[k][0]][x.b+f[k][1]]=0; y.a=x.a+f[k][0]; y.b=x.b+f[k][1]; v.push(y); } } v.pop(); } } int main() { int t,n,m; int i,j,count; scanf("%d",&t); while(t--) { scanf("%d %d",&n,&m); count=0; for(i=1;i<=n;i++) for(j=1;j<=m;j++) scanf("%d",&map[i][j]); for(i=1;i<=n;i++) for(j=1;j<=m;j++) if(map[i][j]) { count++; map[i][j]=0; BFS(i,j); } printf("%d\n",count); } return 0; }
标签:dfs bfs algorithm map struct
原文地址:http://blog.csdn.net/holyang_1013197377/article/details/40868191