bear Baby loves sleeping
题目描述
Sleeping is a favorite of little bearBaby, because the wetness of Changsha in winter is too uncomfortable. One morning, little bearBaby accidentally overslept. The result of being late is very serious. You are the smartest artificial intelligence. Now little bearBaby asks you to help him figure out the minimum time it takes to reach the teaching building.
The school map is a grid of n*m, each cell is either an open space or a building (cannot pass), and the bedroom of little bearBaby is at (1,1)—— the starting point coordinates.The teaching building is at (x, y)——the target point coordinates, he can only go up, down, left or right, it takes 1 minute for each step. The input data ensures that the teaching building is reachable.
输入描述
The first line has two positive integers n, m , separated by spaces(1 <= n, m <= 100), n for the row, m for the column
Next there are two positive integers x, y, separated by spaces(1 <= x <= n, 1 <= y <= m) indicating the coordinates of the teaching building
Next is a map of n rows and m columns, 0 indicate a open space and 1 indicate a obstacles.
输出描述
For each test case, output a single line containing an integer giving the minimum time little bearBaby takes to reach the teaching building, in minutes.
示例输入
5 4
4 3
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
输出
7
说明
For the input example, you could go like this:
(1,1)–>(1,2)–>(2,2)–>(2,3)–>(2,4)–>(3,4)–>(4,4)–>(4,3),so the minimum time is 7.
备注
First grid in the upper left corner is(1,1)
解:
很基础的bfs题,熟悉bfs很容易就能做出来
#include<bits/stdc++.h>
#include<string.h>
#include<queue>
using namespace std;
int inf=1000000;//用一个很大的数赋值满地图,方便计数
int m,n,i,j,t,k,xx,yy,a[101][101],b[101][101];
int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};//用于遍历上下左右四个方向
typedef pair<int,int> pp;//将坐标定义为一对数据
int bfs()
{
pp p;//定义一个成对的变量
queue<pp> que; //定义一个元素成对的队列
que.push(pp(1,1));//将起点推入队列
b[1][1]=0;//将起点赋值为0
while(que.size())//队列长度不为0就继续循环
{
p=que.front();que.pop();//取出队列第一个数
if(p.first==xx&&p.second==yy) break;//如果取出的是终点坐标,则跳出循环
for(i=0;i<4;i++)//遍历四个方向
{
int nx=p.first+dx[i],ny=p.second+dy[i];
if(nx>=1&&ny>=1&&nx<=n&&ny<=m&&a[nx][ny]!=1&&b[nx][ny]==inf)//不出界,不为障碍物,没有走过的坐标,则继续下一步
{
que.push(pp(nx,ny));//将该坐标推入队列,方便下一次从该坐标开始遍历
b[nx][ny]=b[p.first][p.second]+1;//视为走一步,数值加一
}
}
}
return b[xx][yy];//返回终点的值
}
int main()
{
scanf("%d%d",&n,&m);
scanf("%d%d",&xx,&yy);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
scanf("%d",&a[i][j]);//输入地图
b[i][j]=inf;//全部赋值为一个很大的数inf
}
k=bfs();
printf("%d",k);
}
有什么需要改进的欢迎大佬批评!