标签:洛谷 P1443 int xxx yyy bfs vis include 500
题目: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; }
标签:洛谷,P1443,int,xxx,yyy,bfs,vis,include,500 来源: https://www.cnblogs.com/blockche/p/15655165.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。