本文主要是介绍NYOJ 58 最少步数 【BFS】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题意:不解释。
策略:如题;
这道题可以用深搜也可以用广搜,我以前写的是用的深搜,最近在学广搜,就拿这道题来练练手。
代码:
#include<stdio.h>
#include<string.h>
#include<queue>
using std::queue;
bool vis[20][20];
const int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};//方向
int map[9][9] = {
1,1,1,1,1,1,1,1,1,1,0,0,1,0,0,1,0,1,1,0,0,1,1,0,0,0,1,1,0,1,0,1,1,0,1,1,1,0,0,0,0,1,0,0,1,1,1,0,1,0,1,0,0,1,1,1,0,1,0,1,0,0,1,1,1,0,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,
};
struct Node{int pos[2];//pos[0] = x, pos[1] = yint step;
};
Node st, en;
bool match(Node a, Node b) //判断是不是到达终点
{return (a.pos[0] == b.pos[0]&&a.pos[1] == b.pos[1]);
}
int bfs()
{queue<Node> q;int i, j;memset(vis, 0, sizeof(vis)); q.push(st);vis[st.pos[0]][st.pos[1]] = 1;int ans = 0x3f3f3f3f; //初始化while(!q.empty()){Node u = q.front();if(match(u, en)){ //wa了一次是因为没有判断终点是不是起点ans = u.step;break;}for(i = 0; i < 4; i ++){Node v;v.pos[0] = u.pos[0]+dir[i][0];v.pos[1] = u.pos[1]+dir[i][1];v.step = u.step+1;if(match(v, en)){if(v.step < ans)ans = v.step;}else if(!vis[v.pos[0]][v.pos[1]]&&!map[v.pos[0]][v.pos[1]]){q.push(v);vis[v.pos[0]][v.pos[1]] = 1;}}q.pop();}return ans;
}
int main()
{int t;scanf("%d", &t);while(t --){scanf("%d%d%d%d", &st.pos[0], &st.pos[1], &en.pos[0], &en.pos[1]);st.step = 0;printf("%d\n", bfs());}return 0;
}
题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=58
这篇关于NYOJ 58 最少步数 【BFS】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!