- Sources:D-Drunken Maze
- Abstract:给定
n
×
m
(
12
≤
n
×
m
≤
2
×
1
0
5
,
3
≤
n
,
m
≤
1
0
4
)
n\times m(12\le n\times m\le 2\times 10^5, 3\le n,m\le 10^4)
n×m(12≤n×m≤2×105,3≤n,m≤104)的地图,
#
表示墙壁,.
表示空地,S
表示起点,T
表示终点。要求不能超过连续
3
3
3步走同一方向,不可以通过障碍。起点终点视作空地。问 S
到 T
的最小步数。若无解输出
−
1
-1
−1。 - Keyword:搜索(铜牌题)
- Solution:注意到
n
n
n和
m
m
m非常大,因此无法用结构体存图。改用动态处理队列。设计状态数组
d
i
s
t
dist
dist,注意到图中每个点可通过求解其
i
d
id
id进而将状态数组压至三维。
d
i
s
t
[
i
d
]
[
d
i
r
]
[
c
n
t
]
dist[id][dir][cnt]
dist[id][dir][cnt]代表沿
d
i
r
dir
dir方向上经过
c
n
t
cnt
cnt次到达顶点
i
d
id
id。注意处理当
c
n
t
cnt
cnt到达
3
3
3时不可继续沿此方向继续走。
- Code:实现上可采用
B
F
S
BFS
BFS,或
D
F
S
DFS
DFS+记忆化。下面给出
B
F
S
BFS
BFS实现。
#include<bits/stdc++.h>
using namespace std;
const int MAX=1e4;
const int INF=1e9;
char mapp[MAX][MAX];
int n,m,sy,sx,ty,tx;
struct node{
int y,x,pre_dir,cnt;
};
queue<node>q;
int getid(int y,int x){
return y*m+x;
}
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
bool check1(int y,int x){
return y>=0&&y<n&&x>=0&&x<m&&mapp[y][x]!='#';
}
bool check2(int y,int x){
return x==tx&&y==ty;
}
void bfs(){
vector<vector<vector<int>>>dis(n*m,vector<vector<int>>(4,vector<int>(3,INF)));
for(int i=0;i<4;i++){
int ny=sy+dir[i][0],nx=sx+dir[i][1];
if(check1(ny,nx)){
int id=getid(ny,nx);
if(dis[id][i][0]>1){
dis[id][i][0]=1;
q.push({ny,nx,i,1});
}
}
}
bool f=0;
while(q.size()){
int ans=dis[getid(q.front().y,q.front().x)][q.front().pre_dir][q.front().cnt-1];
if(check2(q.front().y,q.front().x)){
cout<<ans,f=1;
break;
}
for(int i=0;i<4;i++){
int now=0;
if(i==q.front().pre_dir){
now=q.front().cnt+1;
if(now>3) continue;
}else now=1;
int ny=q.front().y+dir[i][0],nx=q.front().x+dir[i][1];
if(check1(ny,nx)){
if(dis[getid(ny,nx)][i][now-1]>ans+1){
dis[getid(ny,nx)][i][now-1]=ans+1;
q.push({ny,nx,i,now});
}
}
}
q.pop();
}
if(!f) cout<<-1;
}
int main(){
ios::sync_with_stdio(0),cin.tie(0);
cin>>n>>m;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++){
cin>>mapp[i][j];
if(mapp[i][j]=='S') sy=i,sx=j;
else if(mapp[i][j]=='T') ty=i,tx=j;
}
bfs();
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具