#include
#include
#define N 200#define M 200int 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;}
Let's look at this again:
#include
#include
#define N 200#define M 200int 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
#include
#include#include
#define N 200#define M 200using 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
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;}