洛谷p1747 好奇怪的游戏 /洛谷p1443 马的遍历

2 篇文章 0 订阅
1 篇文章 0 订阅

 

 

思路:这是一道广搜(bfs)水题!!!

其实这一题和洛谷p1443马的遍历是一样的只不过是在马走日字的基础上增添了马走田字的规则

分别从两个马的位置一直到搜到(1,1)为止,在过程中累加步数,根据广搜层层拓展的原理可知最先搜到(1,1)时一定是最优解

代码:

#include<bits/stdc++.h>
using namespace std;
int dx[13] = { 1,1,2,2,2,2,-1,-1,-2,-2,-2,-2 };//用数组来代替走日字和走田字的规则
int dy[13] = { -2,2,-2,-1,1,2,-2,2,-1,1,-2,2 };
int vis[105][105];
int x1, y2;
struct pos
{
	int x, y, step;//结构体定义位置和步数
};
void bfs()
{
	pos cur, nex;//结构体变量
	queue<pos>qu;//队列
	cur.x = x1, cur.y = y2, cur.step = 0;
	vis[cur.x][cur.y] = 1;
	qu.push(cur);
	while (qu.empty() == false)//队列为空就退出了
	{
		cur = qu.front();
		qu.pop();
		for (int i = 0; i < 13; i++)
		{
			nex.x = cur.x + dx[i];
			nex.y = cur.y + dy[i];
			if (nex.x > 0 && nex.x <= 100 && nex.y > 0 && nex.y <= 100 && vis[nex.x][nex.y] == 0)//判断边界 因为题目是不给边界的所以我们自己开大点
			{
				vis[nex.x][nex.y] = 1;
				nex.step = cur.step + 1;
				qu.push(nex);
				if (nex.x == 1 && nex.y == 1)//走到1 1就输出步数并返回
				{
					cout << nex.step << '\n';
					return;
				}
			}
		}
	}
	return;
}
int main()
{
	ios::sync_with_stdio(false);//给cin提速
	cin.tie(0);
	while (cin >> x1 >> y2)//多组输入
	{
		memset(vis, 0, sizeof(vis));//一定要初始化vis数组 我就wa了一次
		if (x1 == 1 && y2 == 1)//提前判断
		{
			cout << 0 << '\n';
			continue;
		}
		bfs();
	}
	return 0;
}

下面是p1143 马的遍历

思路和上面一模一样

#include<bits/stdc++.h>
using namespace std;
int n, m, x, y;
int vis[404][404], t[404][404];
int dx[8] = { -2,-2,2,2,1,-1,1,-1 };
int dy[8] = { -1,1,-1,1,2,-2,-2,2 };
struct pos
{
	int nx, ny;
};
int main()
{
	memset(t, -1, sizeof(t));
	queue<pos>qu;
	pos cur, nex;
	cin >> n >> m >> x >> y;
	vis[x][y] = 1;
	t[x][y] = 0;
	cur.nx = x;
	cur.ny = y;
	qu.push(cur);
	while (qu.empty() == false)
	{
		cur = qu.front();
		qu.pop();
		for (int i = 0; i < 8; i++)
		{
			nex.nx = cur.nx + dx[i];
			nex.ny = cur.ny + dy[i];
			if (nex.ny > 0 && nex.ny <= m && nex.nx > 0 && nex.nx <= n && vis[nex.nx][nex.ny] == 0)
			{
				t[nex.nx][nex.ny] = t[cur.nx][cur.ny] + 1;
				vis[nex.nx][nex.ny] = 1;
				qu.push(nex);
			}
		}
	}
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			printf("%-5d", t[i][j]);
		}
		cout << '\n';
	}
	return 0;
}

感谢你的观看如果帮助点个赞谢谢!!!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值