[ABC335D] Loong and Takahashi题解 BFS写法
前置知识:BFS(学过的自行跳过)
理论知识
BFS 全称是 Breadth First Search,中文名是宽度优先搜索,也叫广度优先搜索,适用于最短路、联通块等问题。
与DFS不同,DFS会一直遍历到底部,直到走到死路才回溯,很容易 TLE。而 BFS 会一层一层的遍历,找到最优解后马上停止,时间上会比 DFS 快很多。
打个比方:假设有一棵树。
那么,DFS 是这样遍历的(蓝线表示遍历,红线表示回溯)。
而 BFS 是这样遍历的
代码实现
BFS 的实现需要用到一个 STL 容器:队列,就是 queue 。这里就不讲了,想了解就看这里
代码实现:
int dx[5]={0,-1,0,1,0},dy[5]={0,0,-1,0,1};
struct csp{
int x,y,step;
}
int bfs(int x,int y,int step){
queue<csp>q;
q.push((csp){x,y,step});//初始化
while(!q,empty()){
x=q.front().x;
y=q.front().y;
step=q.front().step;
q.pop()//取出当前情况并弹出
if(vis[x][y]) continue;
vis[x][y]=1;//判断走重路
if(x==ex&&y==ey) return step;//判断终点
for(int i=1;i<=4;i++){
int tx=x+dx[i],ty=y+dy[i];
if(/*判断越界和是否可走*/) q.push((csp){tx,ty,step+1});//入队
}
}
return -1;
}正文
这道题就是一个螺旋方阵。详细注释见代码。
#include <iostream>
#include <queue>
using namespace std;
#define FOR(i,j,n,k) for(int i=(j);i<=(n);i+=k)
#define ROR(i,j,n,k) for(int i=(j);i>=(n);i-=k)
int n;
int dx[5]={0,1,0,-1,0},dy[5]={0,0,1,0,-1};//位移数组
int map[100][100];
bool vis[100][100];
struct csp{
int x,y,step,way;
};
void bfs(int x,int y,int way,int step){
queue<csp>q;
map[1][1]=1;//更新起点
q.push((csp){x,y,step,way});
while(!q.empty()){
x=q.front().x;
y=q.front().y;
step=q.front().step;
way=q.front().way;
int tway=0,tx=0,ty=0;
q.pop();//取出当前情况并弹出
if(tx==n/2+1&&ty==n/2+1) return;//终点
if(vis[x][y]) return;//判断重复路线
vis[x][y]=1;
FOR(i,0,3,1){
if(way+i>4) tway=way+i-4;//min(way+i,4)//判断方向越界
else tway=way+i;
tx=x+dx[tway],ty=y+dy[tway];
if(tx>=1&&ty>=1&&tx<=n&&ty<=n&&map[tx][ty]==0)
{//符合条件就入队
map[tx][ty]=step;
q.push((csp){tx,ty,step+1,tway});
break;//能走就结束
}
}
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(),cout.tie();
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
cin>>n;
FOR(i,1,n,1)
FOR(j,1,n,1)
map[i][j]=vis[i][j]=0;//初始化
bfs(1,1,1,2);
FOR(i,1,n,1){
FOR(j,1,n,1)
if(map[i][j]<n*n) cout<<map[i][j]<<" ";
else cout<<"T ";//特判高桥的位置
cout<<"\n";
}
return 0;
}

