标签:y2 20 题锦 X2 BFS x2 搜索 y1 x1
BFS是搜索中经常考察的一种搜索方式。
题目:
两个图一起搜索,上下同步,左右相反,可以一个动一个不动,两张图的大小都是20
分析:
用个四维来写,差点没写死我。明明很简单的题目,从早上七点一直写到下午四点。
代码:
#include <bits/stdc++.h> #define rep(i, a, b) for (int i = a; i <= b; i ++ ) using namespace std; const int N = 25; char g1[N][N], g2[N][N]; bool st[N][N][N][N]; struct Node{ int x1, y1, x2, y2; }pre[N][N][N][N]; int dx[4] = {1, 0, 0, -1}, dy[8] = {0, -1, 1, 0, 0, 1, -1, 0}; char c[10] = {'D', 'L', 'R', 'U'}; void bfs(int x1, int y1, int x2, int y2) { queue<Node> q; q.push({x1, y1, x2, y2}); st[x1][y1][x2][y2] = true; while (q.size()) { Node t = q.front(); q.pop(); // printf("[%d, %d], [%d, %d]\n", t.x1, t.y1, t.x2, t.y2); if (t.x1 == 1 && t.y1 == 20 && t.x2 == 1 && t.y2 == 1) break; rep(i, 0, 3) { x1 = t.x1 + dx[i], y1 = t.y1 + dy[i], x2 = t.x2 + dx[i], y2 = t.y2 + dy[i + 4]; if (x1 <= 0 || x1 > 20 || y1 <= 0 || y1 > 20 || g1[x1][y1] == '#') x1 = t.x1, y1 = t.y1; if (x2 <= 0 || x2 > 20 || y2 <= 0 || y2 > 20 || g2[x2][y2] == '#') x2 = t.x2, y2 = t.y2; if (!st[x1][y1][x2][y2]) { // printf("[%d, %d], [%d, %d]\n", x1, y1, x2, y2); q.push({x1, y1, x2, y2}); st[x1][y1][x2][y2] = true; pre[x1][y1][x2][y2] = t; } } } #if 1 x1 = 1, y1 = 20, x2 = 1, y2 = 1; string ans; g1[x1][y1] = g2[x2][y2] = 'A'; // printf("[%d, %d], [%d, %d]\n", x1, y1, x2, y2); while (x1 != 20 || y1 != 20 || x2 != 20 || y2 != 1) { Node t = pre[x1][y1][x2][y2]; g1[t.x1][t.y1] = g2[t.x2][t.y2] = 'A'; // printf("now : [%d, %d], [%d, %d]\n", x1, y1, x2, y2); // printf("pre : [%d, %d], [%d, %d]\n", t.x1, t.y1, t.x2, t.y2); rep(i, 0, 3) { int X1 = t.x1 + dx[i], Y1 = t.y1 + dy[i]; int X2 = t.x2 + dx[i], Y2 = t.y2 + dy[i + 4]; // printf("%c direction: [%d, %d], [%d, %d]\n", c[i], X1, Y1, X2, Y2); if (X1 <= 0 || X1 > 20 || Y1 <= 0 || Y1 > 20 || g1[X1][Y1] == '#') X1 = t.x1, Y1 = t.y1; if (X2 <= 0 || X2 > 20 || Y2 <= 0 || Y2 > 20 || g2[X2][Y2] == '#') X2 = t.x2, Y2 = t.y2; if (X1 == x1 && Y1 == y1 && X2 == x2 && Y2 == y2) { ans += c[i]; break; } } x1 = t.x1, y1 = t.y1, x2 = t.x2, y2 = t.y2; } cout << ans.size() << endl; reverse(ans.begin(), ans.end()); cout << ans << endl; rep(i, 1, 20) { cout << g1[i] + 1 << " " << g2[i] + 1 << endl; } #endif } int main() { rep(i, 1, 20) { rep(j, 1, 20) cin >> g1[i][j]; rep(j, 1, 20) cin >> g2[i][j]; } bfs(20, 20, 20, 1); return 0; }
标签:y2,20,题锦,X2,BFS,x2,搜索,y1,x1 来源: https://www.cnblogs.com/Iamcookieandyou/p/15109400.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。