52分求助
查看原帖
52分求助
576639
woshishabi11451444楼主2023/8/3 21:16
#include<bits/stdc++.h>

using namespace std;

const int N = 400;
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};

struct node{
  int x, y, step;
}stk[N * N];

struct sp{
  int ax, ay, bx, by;
}a[30];

char mp[N][N];

int n, m, head = 1, tail, sx, sy, vis[N][N];

void Record(int x, int y, int step){
  if(x < 1 || x > n || y < 1 || y > m || mp[x][y] == '#' || vis[x][y]){
    return ;
  }
  vis[x][y] = 1;
  if(mp[x][y] >= 'A' && mp[x][y] <= 'Z'){
    int v = mp[x][y] - 'A';
    if(a[v].ax == x && a[v].ay == y){
      stk[++tail] = {a[v].bx, a[v].by, step};
      vis[a[v].bx][a[v].by] = 1;
    }
    else{
      stk[++tail] = {a[v].ax, a[v].ay, step};
      vis[a[v].ax][a[v].ay] = 1;
    }
  }
  else{
    stk[++tail] = {x, y, step};
  }
}

int main(){
  cin >> n >> m;
  for(int i = 1; i <= n; i++){
    cin >> mp[i] + 1;
    for(int j = 1; j <= m; j++){
      if(mp[i][j] == '@'){
        sx = i;
        sy = j;
      }
    }
  }
  for(int i = 1; i <= n; i++){
    for(int j = 1; j <= m; j++){
      if(mp[i][j] >= 'A' && mp[i][j] <= 'Z'){
        if(!a[mp[i][j] - 'A'].ax){
          a[mp[i][j] - 'A'].ax = i;
          a[mp[i][j] - 'A'].ay = j;
        }
        else{
          a[mp[i][j] - 'A'].bx = i;
          a[mp[i][j] - 'A'].by = j;
        }
      }
    }
  }
  Record(sx, sy, 0);
  while(head <= tail){
    node q = stk[head++];
    if(mp[q.x][q.y] == '='){
      cout << q.step;
      return 0;
    }
    for(int i = 0; i < 4; i++){
      Record(q.x + dx[i], q.y + dy[i], q.step + 1);
    }
  }
  return 0;
}

2023/8/3 21:16
加载中...