UVA 572 DFS(floodfill) 用DFS求連通塊
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64uDescription
Due to recent rains, water has pooled in various places in Farmer John's field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water ('W') or dry land ('.'). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors.Input
* Line 1: Two space-separated integers: N and MOutput
* Line 1: The number of ponds in Farmer John's field.Sample Input
10 12 W........WW. .WWW.....WWW ....WW...WW. .........WW. .........W.. ..W......W.. .W.W.....WW. W.W.W.....W. .W.W......W. ..W.......W.
Sample Output
3
Hint
OUTPUT DETAILS:
題解:輸入m行n列的字符矩陣,統計字符“W”組成多少個八連塊。如果兩個字符“W”所在的格子相鄰(橫,豎或者對角線方向),就說它們屬於同一個八連塊,采用二重循環來找。
這就是連通塊原理;每訪問一次“W”,就給它寫上標記的編號,方便檢查。
AC代碼:
#include<cstdio> #include<cstring> const int maxn=1000+5; char tu[maxn][maxn]; //輸入圖的數組 int m,n,idx[maxn][maxn]; //標記數組 void dfs(int r,int c,int id) { if(r<0||r>=m||c<0||c>=n) return; if(idx[r][c]>0||tu[r][c]!='W') return; idx[r][c]=id; for(int dr=-1; dr<=1; dr++) for(int dc=-1; dc<=1; dc++) // 尋找周圍八塊 if(dr!=0||dc!=0) dfs(r+dr,c+dc,id); } int main() { int i,j; while(scanf("%d%d",&m,&n)==2&&m&&n) { for(i =0; i<m; i++) scanf("%s",tu[i]); memset(idx,0,sizeof(idx)); int q=0; for(i=0; i<m; i++) for(j=0; j<n; j++) if(idx[i][j]==0&&tu[i][j]=='W') dfs(i,j,++q); printf("%d\n",q); } return 0; }