NYOJ27.水池數目-DFS求連通塊
阿新 • • 發佈:2018-06-04
amp namespace others 標識 style OS clu isp 一個
水池數目
時間限制:3000 ms | 內存限制:65535 KB 難度:4- 描述
- 南陽理工學院校園裏有一些小河和一些湖泊,現在,我們把它們通一看成水池,假設有一張我們學校的某處的地圖,這個地圖上僅標識了此處是否是水池,現在,你的任務來了,請用計算機算出該地圖中共有幾個水池。
- 輸入
- 第一行輸入一個整數N,表示共有N組測試數據
每一組數據都是先輸入該地圖的行數m(0<m<100)與列數n(0<n<100),然後,輸入接下來的m行每行輸入n個數,表示此處有水還是沒水(1表示此處是水池,0表示此處是地面) - 輸出
- 輸出該地圖中水池的個數。
要註意,每個水池的旁邊(上下左右四個位置)如果還是水池的話的話,它們可以看做是同一個水池。 - 樣例輸入
-
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
- 代碼:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 #include<algorithm> 6 #include<queue> 7 #include<vector> 8 using namespace std; 9 typedef longlong ll; 10 const int maxn=100+10; 11 int a[maxn][maxn]; 12 int dir[4][2]={-1,0,1,0,0,1,0,-1}; 13 int n,m,num; 14 void DFS(int x,int y){ 15 a[x][y]=0; 16 for(int i=0;i<4;i++){ 17 int dx=x+dir[i][0]; 18 int dy=y+dir[i][1]; 19 if(dx>=0&&dy>=0&&dx<n&&dy<m&&a[dx][dy])20 DFS(dx,dy); 21 } 22 } 23 int main(){ 24 int t; 25 scanf("%d",&t); 26 while(t--){ 27 num=0; 28 scanf("%d%d",&n,&m); 29 memset(a,0,sizeof(a)); 30 for(int i=0;i<n;i++){ 31 for(int j=0;j<m;j++) 32 scanf("%d",&a[i][j]); 33 } 34 for(int i=0;i<n;i++){ 35 for(int j=0;j<m;j++){ 36 if(a[i][j]==1){ 37 DFS(i,j); 38 num++; 39 } 40 } 41 } 42 printf("%d\n",num); 43 } 44 return 0; 45 }
NYOJ27.水池數目-DFS求連通塊