POJ 2386 Lake Counting DFS
阿新 • • 發佈:2018-06-22
blank AI bits c++ problem http std 深搜 AR
題目鏈接:http://poj.org/problem?id=2386
思路很簡單,就是一個標準的DFS,不斷從W開始遍歷,每遍歷一個W就改成".",然後朝八個方向深搜,要註意邊界。如果八個方向都搜完了,一次深搜就結束了。
那麽進行幾次深搜就意味著有幾個連通的區域。
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int maxn = 105; 4 int N,M; 5 char field[maxn][maxn]; 6 7 void dfs(int x,int y){ 8 field[x][y] = ‘.‘; 9 10 for(int i=-1;i<=1;++i){ 11 for(int j=-1;j<=1;++j){ 12 int a = x+i, b = y+j; 13 if(a>=0 && a<N && b>=0 && b<M && field[a][b] == ‘W‘) 14 dfs(a,b); 15 } 16 } 17 return ; 18} 19 20 int main(){ 21 cin>>N>>M; 22 for(int i=0;i<N;++i){ 23 for(int j=0;j<M;j++) 24 cin>>field[i][j]; 25 } 26 int ans = 0; 27 for(int i=0;i<N;++i){ 28 for(int j=0;j<M;++j){ 29 if(field[i][j] == ‘W‘){ 30 dfs(i,j);31 ans++; 32 } 33 } 34 } 35 cout<<ans; 36 return 0; 37 }
POJ 2386 Lake Counting DFS