首页 > 其他 > 详细

P1747 好奇怪的游戏(结构体化,bfs)

时间:2021-04-03 13:28:26      阅读:26      评论:0      收藏:0      [点我收藏+]
//这道题学到了如何结构体化,把变量强行转变成一个结构体并推入队列中
//两个变量的化,可以采用make_pair的方式
//一开始想用暴搜,但是暴搜情况下,回溯会影响最短路
//一般情况下,求最短路的时候,都用bfs,而非dfs
//这题还有个隐性条件就是不能越界,棋盘就那么大
#include <iostream> #include <set> #include <vector> #include <cmath> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> #define ll long long using namespace std; int vis[60][60];//定义点是否使用过 int dx[12] = { 1,1,2,2,2,2,-1,-1,-2,-2,-2,-2 }, dy[12] = { -2,2,-2,-1,1,2,-2,2,-1,1,-2,2 };//十二个方向 struct node { int x, y, step;//坐标和此时的步长 node(int a=0,int b=0,int c=0){//我也不太清楚,反正必须这么写一个内结构体,把x,y,step归零,后面才能结构体化,否则会报错 x=a;y=b;step=c;} }; queue<node> q; int ans; int n, m; inline int bfs(int x, int y) { q.push(node(x, y, 0)); vis[x][y] = 1; while (!q.empty()) { node t = q.front(); q.pop();//记得删除 for (int i = 0; i < 12; i++) { int tx = t.x + dx[i]; int ty = t.y + dy[i]; if (tx >= 1 && ty >= 1 && tx <= 50 && ty <= 50 && !vis[tx][ty]) { q.push(node(tx, ty, t.step + 1));//推入 vis[tx][ty] = 1; } if (tx == n && ty == m) return t.step + 1;直接返回
        //因为兄弟节点具有实时性,每个点在同一个队列中时,他们的step都是相同的,只有一个点到了1,1,就已经是最快的了 } } }
int main() { cin >> n>> m; cout << bfs(1, 1)<<endl;//从1,1,开始搜索 while (!q.empty()) q.pop();//记住一定要删除, memset(vis, 0, sizeof(vis));//归零 cin >> n >> m; cout << bfs(1, 1)<<endl; return 0; }

 

P1747 好奇怪的游戏(结构体化,bfs)

原文:https://www.cnblogs.com/BlogBaudelaire/p/14613323.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!