POJ 1979 Red and Black

本文提供了一道经典的深度优先搜索(DFS)算法题目解析,通过一个具体的例子介绍了如何使用DFS来解决特定类型的问题。该示例包括了完整的C语言代码实现,演示了如何遍历地图并标记已访问区域。

http://poj.org/problem?id=1979

DFS模板题.

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 int W,H;
 5 char map[22][22];
 6 int count=0;
 7 bool check(int x,int y)
 8 {
 9     if(!(1<=x&&x<=H&&1<=y&&y<=W))    return false;
10     return true;
11 }
12 void dfs(int x,int y)
13 {
14     if(!check(x,y))    return ;
15     if(map[x][y]=='.'||map[x][y]=='@') {
16         count++;
17         map[x][y]='#';
18         dfs(x,y-1);
19         dfs(x-1,y);
20         dfs(x,y+1);
21         dfs(x+1,y);
22     }
23 }
24 int main()
25 {
26     while(scanf("%d%d",&W,&H)!=EOF) {
27         if(W==H&&W==0)    return 0;
28         int i,j,start_x,start_y;
29         for(i=1;i<=H;i++) { 
30             getchar();
31             for(j=1;j<=W;j++) {
32                 scanf("%c",&map[i][j]);
33                 if(map[i][j]=='@') {
34                     start_x=i;
35                     start_y=j;
36                 }
37             }
38         }
39         count=0;
40         dfs(start_x,start_y);
41         printf("%d\n",count);
42     }
43 }    

 

转载于:https://www.cnblogs.com/yangce/archive/2013/02/14/2911143.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值