HDU 1312 Red and Black(经典DFS)

本文深入讲解了一道经典的深度优先搜索(DFS)算法题,通过设置上下左右四个方向,从起点开始遍历,无需回溯,最终求解路径覆盖的问题。文章提供了详细的AC代码实现,包括读取起点、设置边界条件、判断状态等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

嗯...

 

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1312

 

一道很经典的dfs,设置上下左右四个方向,读入时记下起点,然后跑dfs即可...最后答案加上起点的1,无需回溯!!

 

AC代码:

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 
 5 using namespace std;
 6 
 7 int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
 8 
 9 int n, m, ans;
10 bool flag[25][25];
11 char g[25][25];
12 
13 inline void dfs(int x, int y){
14     for(int i = 0; i < 4; i++){
15         int nx = x + dir[i][0];
16         int ny = y + dir[i][1];
17         if(nx <= m && ny <= n && nx > 0 && ny > 0 && !flag[nx][ny] && g[nx][ny] == '.'){
18             ans++;
19             flag[nx][ny] = 1;
20             dfs(nx, ny);
21         }
22     }
23 }
24 
25 int main(){
26     while(~scanf("%d%d", &n, &m) && n != 0 && m != 0){
27         int x, y;
28         memset(flag, 0, sizeof(flag));
29         for(int i = 1; i <= m; i++){
30             for(int j = 1; j <= n; j++){
31                 cin >> g[i][j];
32                 if(g[i][j] == '@'){ x = i; y = j;}
33             }
34         }
35         ans = 0;
36         flag[x][y] = 1;
37         dfs(x, y);
38         printf("%d\n", ans + 1);
39     }
40     return 0;
41 }
42     
AC代码

 

转载于:https://www.cnblogs.com/New-ljx/p/11436787.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值