显然的 bfs。
定义状态 为:坐标 ,方向 ( 往右, 往下, 往左, 往上),已经走了 步。
然后首先从 开始反射。
由于 只能往右或下,所以将 状态和 扔进 queue,其中 为是否需要修改当前格子以到达期望位置。
然后就是 bfs 转移了。枚举改成的状态为 (如果本来就是这个就不用增加步数)然后实行对应的 push 即可。
看着很简单?并非,接下来是一大堆细节。
- 需要特判 的情况,不特判会 WA * 2;
- 到终点格子时一定要把方向扭到右。如果你懒,直接使用
ans+(f(dir,v[n][m])!=0)并直接输出会被 hack(因为可能有后面的节点不用转方向),所以要取 然后最后输出。 - 方向转移比较难写,但是之前用这么特殊的方式定义方向是有用的。可以发现碰到 B 棱镜时将 异或上 、碰到 C 棱镜时将 异或上 就可以快速的转移方向了。代码里由于方便写了一个函数专门转方向;
- 需要判断转方向后会不会超界。
code(使用 deque 进行 01bfs)
#include<bits/stdc++.h>
#define int long long
using namespace std;
struct node{int x,y,dir,d;};
int dx[]={0,1,0,-1},dy[]={1,0,-1,0};//方向
int f(int dir,char c){if(c=='A') return dir;if(c=='B') return dir^1;return dir^3;}//转向
void solve(){
int n,m,ndir,nx,ny,nd;
cin>>n>>m;
vector<string>v(n+3);
vector<vector<vector<int>>>dis(n+3,vector<vector<int>>(m+3,vector<int>(4,1e18)));
for(int i=1;i<=n;i++) cin>>v[i],v[i]=" "+v[i];
if(n==1&&m==1){//细节 1
if(v[1][1]=='A') cout<<"0\n";
else cout<<"1\n";
return;
}
deque<node>q;
q.push_front({1,2,0,(v[1][1]!='A')});
q.push_front({2,1,1,(v[1][1]!='B')});
dis[1][2][0]=(v[1][1]!='A');
dis[2][1][1]=(v[1][1]!='B');
int ans=1e18;
while(!q.empty()){
auto [x,y,dir,d]=q.front();q.pop_front();
if(x>n||y>m||x<1||y<1) continue;//细节 4
if(ans+1<d) break;
if(x==n&&y==m) ans=min(ans,d+(f(dir,v[n][m])!=0));//细节 2
ndir=f(dir,v[x][y]),nx=x+dx[ndir],ny=y+dy[ndir],nd=d;
if(1<=nx&&nx<=n&&1<=ny&&ny<=m&&dis[nx][ny][ndir]>nd)
dis[nx][ny][ndir]=nd,q.push_front({nx,ny,ndir,nd});
for(auto C:{'A','B','C'}) if(v[x][y]!=C){
ndir=f(dir,C),nx=x+dx[ndir],ny=y+dy[ndir],nd=d+1;
if(1<=nx&&nx<=n&&1<=ny&&ny<=m&&dis[nx][ny][ndir]>nd)
dis[nx][ny][ndir]=nd,q.push_back({nx,ny,ndir,nd});
}
}
cout<<ans<<"\n";
}
signed main(){
cin.tie(0)->sync_with_stdio(0);
int t;cin>>t;
while(t--) solve();
}优先队列 bfs 复杂度较劣且刚学 01 bfs,所以赛时没写这东西,所以代码留给别的题解。