Number of nyoj27 pools (DFS) and number of nyoj27 pools dfs
- Question 27
- Question Information
- Running result
- Rankings
- Discussion board
Pool quantity time limit: 3000 MS | memory limit: 65535 KB difficulty: 4
-
Description
-
There are some small rivers and some lakes on the campus of Nanyang Institute of Technology. Now we take them all as pools. Suppose there is a map somewhere in our school, this map only identifies whether it is a pool. Now, your task is coming. Please use a computer to figure out several pools in the map.
-
Input
-
Enter an integer N in the first line, indicating that there are N groups of test data.
For each set of data, the number of rows m (0 <m <100) and number of columns n (0 <n <100) of the map are input first. Then, enter n numbers per line in the next m line, indicating whether there is water or no water here (1 indicates the pool, 0 indicates the ground)
-
Output
-
Output The number of pools in the map.
Note that, if the pool is still located next to each pool (up or down the four locations), they can be seen as the same pool.
-
Sample Input
-
23 41 0 0 0 0 0 1 11 1 1 05 51 1 1 1 00 0 1 0 10 0 0 0 01 1 1 0 00 0 1 1 1
-
Sample output
-
23
-
Source
-
[Zhang yuncong] original
-
Uploaded
-
Zhang yuncong
Traverse the map to find the pool, and then search it in depth, mark all the pools next to it, and the number of pools + 1
Very simple. But remember that this is the top, bottom, and left directions .. It is not 0.0 in eight directions.
#include <stdio.h>#include <string.h>int t,m,n,i,j,count;int visit[100][100],a[100][100];void dfs(int s1,int s2){if(s1<0||s1==m||s2<0||s2==n||visit[s1][s2]||!a[s1][s2])return ;visit[s1][s2]=1;dfs(s1+1,s2);dfs(s1-1,s2);dfs(s1,s2-1);dfs(s1,s2+1);}int main(){scanf("%d",&t);while(t--){scanf("%d %d",&m,&n);memset(a,0,sizeof(a));memset(visit,0,sizeof(visit));for(i=0;i<m;i++)for(j=0;j<n;j++)scanf("%d",&a[i][j]);count=0;for(i=0;i<m;i++)for(j=0;j<n;j++){if(a[i][j]==1&&visit[i][j]==0)count++,dfs(i,j);}printf("%d\n",count);}}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.