这道题是一道bfs基础题
bfs的基本实现思路就是如上图所示,然后来看题目,这道题其实就是说有很多种走法,但是要选出一种最近的方法,就是说暴力搜索出所有的走法,选一条最近的,那么看代码。
就是用一个a的二维数组来存地图,b的二维数组来记录走的每个格子的步数,就是说如果可以走这一格那就在前一步的基础上加一,然后谁先走到{x,y}就跳出循环,
思路有了,上代码,就是说先
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<int,int> PII;
const int N=110;
int a[N][N];
int b[N][N];
int n,m;
int dfs(){
int x,y,i;
queue<PII> q;
memset(b,-1,sizeof b);
q.push({0,0});
b[0][0]=0;
//四个方向,上下左右
int dx[4]={-1,1,0,0},dy[4]={0,0,-1,1};
//就是队列的长度,当队列的长度大于0时就继续循环,当走到{x,y}的时候,队列的元素就全出栈了
while(q.size()>0){
//出队列
auto t=q.front();
q.pop();
int f=t.first;
int s=t.second;
//循环四次将每个方向,走一步,将所有情况搜索一遍
for(i=0;i<4;i++){
x=dx[i]+f;
y=dy[i]+s;
//就是说不能出地图,还有要保证在地图里可以走(a[x][y]==0)
//还要没走过,b[x][y]==-1
if(x<n && x>=0 && y<m && y>=0 && a[x][y]==0 && b[x][y]==-1){
b[x][y]=b[f][s]+1;
q.push({x,y});
}
}
}
return b[n-1][m-1];
}
int main(){
cin>>n>>m;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cin>>a[i][j];
int sum=dfs();
cout<<sum;
return 0;
}