【DFS】【AOJ-61】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.
Given a diagram of Farmer John's field, determine how many ponds he has.
Input
Line1: Two space-separated integers: N and M 
Lines2..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.
Lines2..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
思路:
还是没啥好说的...深度优先搜索  不明白的翻数据结构图那部分
参考代码:
#include <stdio.h>  
#include <string.h>  
int visited[111][111],movex[8]={-1,-1,0,1,1,1,0,-1},movey[8]={0,-1,-1,-1,0,1,1,1},nx[100000],ny[100000];  
char map[111][111]; 
void dfs(int i,int j);  
int main()  
{  
    int n,m;  
    scanf("%d%d",&n,&m);  
    int i,j;  
    memset(map,-1,sizeof(map));  
    memset(visited,0,sizeof(visited));  
 /*   for(i=1;i<=n;i++)  
    {  
        for(j=1;j<=m;j++)  
        {  
            char temp;  
            scanf("%c",&temp);  
            if(temp=='.')  
                map[i][j]=0;  
            else 
                map[i][j]=1;  
        }  
        getchar();  
    } */
    memset(map,0,sizeof(map)); 
    for(int i = 1;i <= n;i ++) 
        scanf("%s",&map[i][1]); 
    int num=0;  
    for(i=1;i<=n;i++)  
    {  
        for(j=1;j<=m;j++)  
        {  
            if(map[i][j]=='W'&&!visited[i][j])  
            {  
                num++;  
                dfs(i,j);  
            }  
        }  
    }  
    printf("%d\n",num);  
    return 0;  
}  
    
void dfs(int i,int j)  
{  
    visited[i][j]=1;  
    int k;  
    for(k=0;k<8;k++)  
    {  
        if(map[i+movex[k]][j+movey[k]]=='W'&&!visited[i+movex[k]][j+movey[k]])  
            dfs(i+movex[k],j+movey[k]);  
        else
            continue;  
    }  
}  
       
                    
                
                
            
        
浙公网安备 33010602011771号