【bfs】洛谷 P1443 马的遍历
2024-10-19 17:13:16
题目:P1443 马的遍历 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
记录一下第一道ac的bfs,原理是利用队列queue记录下一层的所有点,然后一层一层遍历;
其中:
1.pair<,>可以将两个数据类型压缩成一个数据压进队列里,在表示二维坐标时好用。
2.setw()可以设置输出的宽度,left可以设置为左对齐。
代码:
#include <iostream>
#include <queue>
#include <iomanip>
using namespace std;
typedef long long ll;
queue<pair<int, int>> a;
ll f[500][500], vis[500][500];
int dx[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
int dy[9] = {1, 2, 2, 1, -1, -2, -2, -1};
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m, x, y;
cin >> n >> m >> x >> y;
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= m; ++j)
{
f[i][j] = -1;
}
}
f[x][y] = 0;
vis[x][y] = 1;
a.push(make_pair(x, y));
while (!a.empty())
{
int xx = a.front().first, yy = a.front().second;
a.pop();
for (int i = 0; i < 8; ++i)
{
int xxx = xx + dx[i], yyy = yy + dy[i];
if (xxx < 1 || xxx > n || yyy < 1 || yyy > m || vis[xxx][yyy])
continue;
f[xxx][yyy] = f[xx][yy] + 1;
a.push(make_pair(xxx, yyy));
vis[xxx][yyy] = 1;
}
}
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= m; ++j)
{
cout << left << setw(5) << f[i][j];
}
cout << endl;
}
return 0;
}
最新文章
- 用cmd重命名.htaccess
- IOS第四天(1:图片的方法和缩小,遮罩层)
- Unity 游戏资源ktx转换png
- nginx php-cgi php
- 【Ruby on Rails学习二】在线学习资料的整理
- [UVA] 11995 - I Can Guess the Data Structure! [STL应用]
- Vim命令快捷键(网摘)
- 如何在MQ中实现支持任意延迟的消息?
- hdu_1034(模拟题)
- Vasya and Binary String(来自codeforces
- 傻瓜式搭建私人网络硬盘——owncloud安装指南
- 用 Anaconda 完美解决 Python2 和 python3 共存问题
- Excel操作小结
- 20180705 fragment
- HDU 6333 Harvest of Apples (分块、数论)
- 016.Zabbix聚合监控
- pThreads线程(三) 线程同步--条件变量
- 【AaronYang风格】第一篇 CodeFirst 初恋
- bootstrap datarangepicker如何使用
- spring cloud连载第三篇之Spring Cloud Netflix