您的位置:首页 > 其它

《挑战》2.1 POJ 2386 Lake Counting (简单的dfs)

2015-07-25 00:08 495 查看
# include<cstdio>
# include<iostream>

using namespace std;

# define MAX 123

char grid[MAX][MAX];
int nxt[8][2] = { {1,0},{0,-1},{-1,0},{0,1},{1,1},{1,-1},{-1,1},{-1,-1} };
int n,m;

int can_move( int x,int y )
{
if ( x>=0&&x<n&&y>=0&&y<m )
{
if ( grid[x][y]=='W' )
return 1;
}
return 0;
}

void dfs ( int x,int y )
{
grid[x][y] = '.';
for ( int i = 0;i < 8;i++ )
{
int n_x = x+nxt[i][0], n_y = y+nxt[i][1];
if ( can_move(n_x,n_y) )
{
dfs(n_x,n_y);
}
}
return;
}

int main(void)
{
//int n,m;
int res;
while ( scanf("%d%d",&n,&m)!=EOF )
{
res = 0;
for ( int i = 0;i < n;i++ )
scanf("%s",grid[i]);
for ( int i = 0;i < n;i++ )
{
for ( int j = 0;j < m;j++ )
{
if ( grid[i][j]=='W' )
{
dfs(i,j);
res++;
}
}
}
printf("%d\n",res);
}

return 0;
}


A - Lake Counting
Crawling in process... Crawling failed Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u

Submit Status Practice POJ 2386

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

* 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 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.

题目大意:

  就是说一个n*m的网格中,求出联通块的个数。

解题思路:

  就是一个dfs的基础题,从任意一个满足要求的点开始dfs,求出直到不能走动为止,res++。

复杂度:

  O(8*m*n)

代码:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: