POJ 3248 Catch That Cow

本文介绍了一种使用二维BFS算法解决寻找最短路径问题的方法。通过定义结构体存储位置和步数,利用队列进行广度优先搜索,并判断是否到达目标位置。适用于解决如寻找从起点到终点的最短步数等问题。

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

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

二维BFS

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 #include <queue>
 5 #define READ() freopen("in.txt", "r", stdin);
 6 
 7 using namespace std;
 8 
 9 struct Loc
10 {
11     int x, step;
12     Loc () {}
13     Loc(int x, int step) : x(x), step(step) {}
14 };
15 
16 int N, K;
17 bool use[100007];
18 bool OK(int x)
19 {
20     if (x < 0 || x > 100000 ) return false;
21     else return true;
22 }
23 int bfs()
24 {
25     queue<Loc> que;
26     que.push(Loc(N, 0));
27     while (!que.empty())
28     {
29         Loc crt = que.front();
30         que.pop();
31         if(use[crt.x]) continue;
32         use[crt.x] = true;
33         int nx = crt.x - 1;
34         if (OK(nx) && !use[nx])
35         {
36             if (nx == K) return crt.step+1;
37             else que.push(Loc(nx, crt.step+1));
38         }
39         nx = crt.x + 1;
40         if (OK(nx))
41         {
42             if (nx == K && !use[nx]) return crt.step+1;
43             else que.push(Loc(nx, crt.step+1));
44         }
45         nx = 2*crt.x;
46         if (OK(nx) && !use[nx])
47         {
48             if (nx == K) return crt.step+1;
49             else que.push(Loc(nx, crt.step+1));
50         }
51     }
52 }
53 int main()
54 {
55     //READ()
56     scanf("%d%d", &N, &K);
57     if (N == K) //有N == K的坑点 严谨一点
58     {
59         cout << 0 << endl;
60         return 0;
61     }
62     memset(use, 0, sizeof(use));
63     int ans = bfs();
64     cout << ans << endl;
65     return 0;
66 }

 

转载于:https://www.cnblogs.com/oscar-cnblogs/p/6515916.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值