1 #include<iostream>
2 #include<memory.h>
3 using namespace std;
4
5 int map[105][105];
6 bool visit[105][105];
7
8 void dfs(int i, int j)
9 {
10 visit[i][j] = true;
11 if(map[i-1][j] == 1 && !visit[i-1][j]) dfs(i-1,j);
12 if(map[i+1][j] == 1 && !visit[i+1][j]) dfs(i+1,j);
13 if(map[i][j-1] == 1 && !visit[i][j-1]) dfs(i,j-1);
14 if(map[i][j+1] == 1 && !visit[i][j+1]) dfs(i,j+1);
15 map[i][j] = 0;
16 }
17
18
19 int main()
20 {
21 // freopen("in.txt","r",stdin);
22 int t,m,n,i,j;
23 cin>>t;
24 while(t--)
25 {
26 memset(map,0,sizeof(map));
27 memset(visit,false,sizeof(visit));
28 cin>>m>>n;
29 for(i=1; i<=m; ++i)
30 for(j=1; j<=n; ++j)
31 cin>>map[i][j];
32 int k = 0;
33 for(i=1; i<=m; ++i)
34 for(j=1; j<=n; ++j)
35 if(map[i][j])
36 {
37 ++k;
38 //map[i][j] = 0; 上面的visit[]换成map[]也可以
39 dfs(i,j);
40 }
41 cout<<k<<endl;
42 }
43 return 0;
44 }
2 #include<memory.h>
3 using namespace std;
4
5 int map[105][105];
6 bool visit[105][105];
7
8 void dfs(int i, int j)
9 {
10 visit[i][j] = true;
11 if(map[i-1][j] == 1 && !visit[i-1][j]) dfs(i-1,j);
12 if(map[i+1][j] == 1 && !visit[i+1][j]) dfs(i+1,j);
13 if(map[i][j-1] == 1 && !visit[i][j-1]) dfs(i,j-1);
14 if(map[i][j+1] == 1 && !visit[i][j+1]) dfs(i,j+1);
15 map[i][j] = 0;
16 }
17
18
19 int main()
20 {
21 // freopen("in.txt","r",stdin);
22 int t,m,n,i,j;
23 cin>>t;
24 while(t--)
25 {
26 memset(map,0,sizeof(map));
27 memset(visit,false,sizeof(visit));
28 cin>>m>>n;
29 for(i=1; i<=m; ++i)
30 for(j=1; j<=n; ++j)
31 cin>>map[i][j];
32 int k = 0;
33 for(i=1; i<=m; ++i)
34 for(j=1; j<=n; ++j)
35 if(map[i][j])
36 {
37 ++k;
38 //map[i][j] = 0; 上面的visit[]换成map[]也可以
39 dfs(i,j);
40 }
41 cout<<k<<endl;
42 }
43 return 0;
44 }