栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

信息学奥赛一本通 1257:Knight Moves | OpenJudge NOI 2.5 917:Knight Moves

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

信息学奥赛一本通 1257:Knight Moves | OpenJudge NOI 2.5 917:Knight Moves

【题目链接】

ybt 1257:Knight Moves
OpenJudge NOI 2.5 917:Knight Moves

【题目考点】 1. 广搜 迷宫问题 【解题思路】

广搜,迷宫问题。
不同于一般只能上下左右走的迷宫问题,该问题中的移动方式为马走日。只需将方向数组修改为:马走日后到达的位置与当前位置的横纵坐标差值即可,从一个位置出发,通过马走日最多可以到达8个位置。其余部分与一般迷宫问题做法一样。
注意:多组数据,坐标从0开始。

【题解代码】 解法1:广搜
#include
using namespace std;
#define N 305
struct Node
{
	int x, y, s;//到达(x,y)时步数为s 
	Node(){}
	Node(int a, int b, int c):x(a),y(b),s(c){}
};
int l, stx, sty, edx, edy;//(stx,sty)起点,(edx,edy)终点 
bool vis[N][N];//vis[i][j]:(i,j)位置是否访问过 
int dir[8][2] = {{-1,2},{-1,-2},{1,2},{1,-2},{-2,1},{-2,-1},{2,1},{2,-1}};//方向数组:马走日可能到达的位置与当前位置横纵坐标差值 
queue que;
int bfs()//广搜,返回从起点到终点的最少步数 
{
    que = queue();
	vis[stx][sty] = true;
	que.push(Node(stx, sty, 0));
	while(que.empty() == false)
	{
		Node u = que.front();
		que.pop();
		if(u.x == edx && u.y == edy)
			return u.s;
		for(int i = 0; i < 8; ++i)
		{
			int x = u.x + dir[i][0], y = u.y + dir[i][1], s = u.s + 1;
			if(x >= 0 && x < l && y >= 0 && y < l && vis[x][y] == false)
			{
				vis[x][y] = true;
				que.push(Node(x, y, s));
			}
		}
	}
	return 0;
}
int main()
{
	int n;
	cin >> n;
	while(n--)
	{
		cin >> l >> stx >> sty >> edx >> edy;
		memset(vis, 0, sizeof(vis));
		cout << bfs() << endl;
	}
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/875777.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号