题目链接点我跳转
14届蓝桥杯国赛c组 0走方格
这是一道求最短时间的bfs题目,难度适中推荐新手巩固,和
练习一下
代码展示
#include <bits/stdc++.h>
using namespace std;
const int N=1e3+5;
//a数组存储各个点的值,st数组存储起始点到各个点的时间,bl数组标志是否到达过;
int a[N][N],st[N][N],bl[N][N],n;
int bfs(int x,int y){
queue<pair<int,int>>q; //用一个pair队列存储横竖坐标;
bl[x][y]=1,q.push({x,y}); //将原点入队;
while(q.size()){ //判断队列元素个数,不为0则继续跑;
auto t=q.front(); //用一个auto存储队首元素;
q.pop(); //弹出队首元素;
//下边的所有步骤都在寻找以x,y为起点一秒所能到达的所有点;
x=t.first,y=t.second;
int xx,yy; //这里再定义xx,yy而不改变x,y主要是后面状态的时间都是以x,y为起始的
xx=x+1,yy=y; //向下
if(xx<n&&!bl[xx][yy]){
q.push({xx,yy});
st[xx][yy]=st[x][y]+1;
bl[xx][yy]=1;
}
xx=x,yy=y+1;//向右
if(yy<n&&!bl[xx][yy]){
q.push({xx,yy});
st[xx][yy]=st[x][y]+1;
bl[xx][yy]=1;
}
xx=x,yy=y+1;
//遍历以x,y为起始点往两边比他低的点走的状态,然后入队;
for(int i=yy;i<n;i++){
if(a[xx][i]<a[xx][i-1]){
if(!bl[xx][i]){
q.push({xx,i});
st[xx][i]=st[x][y]+1;
bl[xx][i]=1;
}
}else break; //往右走遇到比他大的就退出;
}
for(int i=y-1;i>=0;i--){
if(a[xx][i]<a[xx][i]){
if(!bl[xx][i]){
q.push({xx,i});
st[xx][i]=st[x][y]+1;
bl[xx][i]=1;
}
}else break; //往左走遇到比它大的就退出;
}
}
return st[n-1][n-1]; //返回终点值;
}
int main()
{
cin>>n;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>a[i][j];
}
}
cout<<bfs(0,0)<<endl;
//代码的调试;
// for(int i=0;i<n;i++){
// for(int j=0;j<n;j++){
// cout<<st[i][j]<<' ';
// }
// cout<<endl;
// }
// 请在此输入您的代码
return 0;
}