搜索题锦——BFS

BFS是搜索中经常考察的一种搜索方式。

Penguins

来源:2021牛客暑期多校训练营2

题目:

两个图一起搜索,上下同步,左右相反,可以一个动一个不动,两张图的大小都是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;
}

  

 

 

 

 

 

上一篇:Codeforces Round #767 (Div. 2) 题解


下一篇:八数码(BFS)