UVA 572 DFS (FloodFill) uses DFS to find connected blocks
Time
limit:1000MS
Memory Limit:65536KB
64bit IO Format:%i64d &%i64 U
Description
Due to recent rains, water have pooled in various places in Farmer John ' s field, which was represented by a rectangle of N x M (1 <= N <=; 1 <= M <=) squares. Each square contains the either water (' W ') or dry land ('. '). Farmer John would like to figure out how many ponds has formed in his field. A pond is a connected set of squares with water in them, where a square was considered adjacent to all eight of its NEIGHBO Rs.
Given a diagram of Farmer John ' s field, determine how many ponds he had.
Input
* Line 1:two space-separated integers:n and M
* Lines 2..n+1:m characters per line representing one row of Farmer John ' s field. Each character is either ' W ' or '. '. The characters does not have spaces between them.
Output
* Line 1:the number of ponds in Farmer John ' s field.
Sample Input
12W ..... 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:
There is three ponds:one in the upper left and one in the lower Left,and one along the right side.
Puzzle: Enter the character matrix of the M row N column, and the statistical character "W" to make up the number of eight connected blocks. If the two-character "W" lattice is adjacent (horizontal, vertical, or diagonal), it is said that they belong to the same eight-block, using a double loop to find .
This is the principle of the connected block, each time you visit "W", it will write the tag number, easy to check.
AC Code:
#include <cstdio>#include<cstring>Const intmaxn= ++5;CharTU[MAXN][MAXN];//an array of input graphsintM,N,IDX[MAXN][MAXN];//Tag ArrayvoidDfsintRintCintID) { 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(intdr=-1; dr<=1; dr++) for(intdc=-1; dc<=1; dc++)//looking for around eight blocks if(dr!=0|| dc!=0) DFS (R+dr,c+dc,id);}intMain () {inti,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)); intq=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;}
UVA 572 Oil Deposits oilfield (Dfs seek connectivity block)