POJ 2386 Lake Counting
阿新 • • 發佈:2017-06-02
family 回溯 [0 tab rep sep miss hint pac
來源:http://poj.org/problem?id=2386
Lake Counting
Description 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.Given a diagram of Farmer John‘s field, determine how many ponds he has. Input * Lines 2..N+1: M characters per line representing one row of Farmer John‘s field. Each character is either ‘W‘ or ‘.‘. The characters do not have spaces between them. Output * 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:There are three ponds: one in the upper left, one in the lower left,and one along the right side. Source USACO 2004 November |
題意:題意題意!。!
一句話兩處理解錯誤,,,,, 求一塊田野裏有多少塊水域~~ 裏面最關鍵的一句:A pond is a connected set of squares with water in them, where a square
is considered adjacent to all eight of its neighbors.
開始理解成至少要兩個"W"才算一塊水域---還有方向,僅僅考慮上下左右四個方向,導致一直WA..
題解: DFS(感覺又不是標準的DFS。不須要回溯)....
AC代碼:
#include<iostream> #include<string> using namespace std; int dir[8][2]={ {0,1},{0,-1}, {1,0},{-1,0}, {1,1},{1,-1}, {-1,-1},{-1,1} }; string map[105]; int dx,dy,count=0; bool flag; void dfs(int x,int y){ for(int i=0;i<8;i++){ int tempx=x+dir[i][0],tempy=y+dir[i][1]; if(tempx>=0&&tempx<dx&&tempy>=0&&tempy<dy&&map[tempx][tempy]==‘W‘){ map[tempx][tempy]=‘.‘; dfs(tempx,tempy); } } } int main() { cin>>dx>>dy; for(int i=0;i<dx;i++) cin>>map[i]; for(int i=0;i<dx;i++) for(int j=0;j<dy;j++){ if(map[i][j]==‘W‘){ count++; map[i][j]=‘.‘; dfs(i,j); } } cout<<count<<endl; return 0; }
POJ 2386 Lake Counting