Mine
#include<bits/stdc++.h>
#define int long long
using namespace std;
char g[55][55];
int n,m;
int u[]={-1,-1,0,1,1,1,0,-1},v[]={0,-1,-1,-1,0,1,1,1};
struct node{
int f;
int x;
int y;
};
queue<node> q;
int f[2][55][55],sx,sy,fx,fy;
bool vis[2][55][55],l[55][55];
signed main(){
// freopen("cycle.in","r",stdin);
// freopen("cycle.out","w",stdout);
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>g[i][j];
if(g[i][j]=='X'){
fx=i;
fy=j;
}
if(g[i][j]=='*'){
sx=i;
sy=j;
}
}
}
for(int i=fx+1;i<=n;i++) l[i][fy]=1;
vis[0][sx][sy]=1;
q.push((node){0,sx,sy});
while(!q.empty()){
int ff=q.front().f;
int xx=q.front().x;
int yy=q.front().y;
q.pop();
// cout<<ff<<" "<<xx<<" "<<yy<<"\n";
for(int i=0;i<8;i++){
int nx=xx+u[i];
int ny=yy+v[i];
if(nx<=0||nx>n||ny<=0||ny>m||g[nx][ny]=='X') continue;
if(l[xx][yy]||l[nx][ny]&&(ny<yy)) continue;
if(l[nx][ny]&&!vis[1][nx][ny]){
vis[1][nx][ny]=1;
f[1][nx][ny]=f[ff][xx][yy]+1;
q.push((node){1,nx,ny});
}
else if(!vis[ff][nx][ny]){
vis[ff][nx][ny]=1;
f[ff][nx][ny]=f[ff][xx][yy]+1;
q.push((node){ff,nx,ny});
}
}
}
cout<<f[1][sx][sy];
return 0;
}
正解
#include <bits/stdc++.h>
using namespace std;
const int N = 100 + 10;
const int dir[8][2] = {
{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}
};
struct Node {
int flag, x, y;
};
queue<Node> q;
int f[2][N][N];
bool vis[2][N][N], line[N][N];
int n, m, sx, sy, fx, fy;
char mp[N][N];
int main() {
freopen("cycle.in", "r", stdin);
freopen("cycle.out", "w", stdout);
cin >> n >> m;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j) {
cin >> mp[i][j];
if (mp[i][j] == 'X') {
fx = i;
fy = j;
}
if (mp[i][j] == '*') {
sx = i;
sy = j;
}
}
for (int i = fx + 1; i <= n; ++i) line[i][fy] = true;
vis[0][sx][sy] = true;
q.push((Node){0, sx, sy});
while (!q.empty()) {
int flg = q.front().flag;
int x = q.front().x;
int y = q.front().y;
q.pop();
for (int i = 0; i < 8; ++i) {
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if (nx <= 0 || nx > n || ny <= 0 || ny > m || mp[nx][ny] == 'X') continue;
if ((line[x][y] || line[nx][ny]) && (ny < y)) continue;
if (line[nx][ny] && !vis[1][nx][ny]) {
vis[1][nx][ny] = true;
f[1][nx][ny] = f[flg][x][y] + 1;
q.push((Node){1, nx, ny});
} else if (!vis[flg][nx][ny]) {
vis[flg][nx][ny] = true;
f[flg][nx][ny] = f[flg][x][y] + 1;
q.push((Node){flg, nx, ny});
}
}
}
cout << f[1][sx][sy] << endl;
}
就很离谱