https://ac.nowcoder.com/acm/contest/190/H
就是在节点里保存两个人的坐标,然后两个点同时向周围扩展。vis保存了所有情况的状态,暂时不知道有啥用,可能是个回溯的作用?
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ll;
const int maxn = 2e6 + 5, inf = 0x3f3f3f3f;
char a[5][5];//注意多开个空间存0
int n, m, pa, pb, all;
int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
bool vis[1 << 17][4][4][4][4];
struct node{
int x1, y1, x2, y2, have, time;
};
int getpos(int x, int y){ return 1 << (x * m + y + 1);}
int bfs(int x, int y, int have, int t)
{
queue<node> qe;
qe.push(node{x, y, x, y, have, 0});
while (!qe.empty()){
node e = qe.front(); qe.pop();
if (e.x1 < 0 || e.y1 < 0 || e.x1 >= n || e.y1 >= m) continue;
if (e.x2 < 0 || e.y2 < 0 || e.x2 >= n || e.y2 >= m) continue;
if (a[e.x1][e.y1] == 'X' || a[e.x2][e.y2] == 'X') continue;
if (e.have == all) return e.time;//注意顺序,可能超范围了但是也相等,这时候时间就多1了。
if (vis[e.have][e.x1][e.y1][e.x2][e.y2]) continue;
vis[e.have][e.x1][e.y1][e.x2][e.y2] = 1;
for (int i = 0; i < 4; ++i){
for (int j = 0; j < 4; ++j){
int temp = e.have | getpos(e.x1 + dx[i], e.y1 + dy[i]) | getpos(e.x2 + dx[j], e.y2 + dy[j]);
qe.push(node{e.x1 + dx[i], e.y1 + dy[i], e.x2 + dx[j], e.y2 + dy[j], temp, e.time + 1});
}
}
}
return -1;
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
scanf("%d %d", &n, &m);
for (int i = 0; i < n; ++i) scanf("%s", a[i]);
int sx, sy;
for (int i = 0; i < n; ++i){
for (int j = 0; j < m; ++j){
if (a[i][j] == 'S') sx = i, sy = j;
else if (a[i][j] == 'O') all |= getpos(i, j);
}
}
all |= getpos(sx, sy);
cout << bfs(sx, sy, getpos(sx, sy), 0) << endl;
return 0;
}