题目描述
输入格式
输出格式
数据范围
输入样例
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
输出样例
8
#include <iostream>
#include <queue>
using namespace std;
const int N = 110;
struct node
{
int x,y;
};//结构体存坐标
int n1,m1;
int m[N][N];//map地图
int d[N][N];//到起点的距离
void bfs(int a,int b)
{
queue<node>q;
q.push({a,b});
while(!q.empty())
{
node st=q.front();//记录当前坐标
//cout<<st.x<<","<<st.y<<endl;
q.pop();
m[st.x][st.y]=1;//走过后标记
int dx[4] = {0, 1, 0, -1}, dy[4] = {-1, 0, 1, 0};
for(int i = 0; i < 4; i++)//遍历4个方向
{
int x=st.x+dx[i];
int y=st.y+dy[i];
// cout<<"("<<x<<","<<y<<")"<<" ";
if(m[x][y] == 0&&x>=1&&y>=1&&x<=n1&&y<=m1)//防止越界
{
m[x][y]=1;//标记
d[x][y]=d[st.x][st.y]+1;//下一个距离+1
q.push({x,y});//如果能走,存入该方向的点
}
}
}
cout<<d[n1][m1];
}
int main()
{
cin>>n1>>m1;
for(int i = 1; i <= n1; i++)
{
for(int j = 1; j <= m1; j++)
{
cin >> m[i][j];
}
}
bfs(1,1);
return 0;
}
bfs模板题,从起点开始广搜,记录下一点到起点的距离