B bearBaby loves sleeping
阿新 • • 發佈:2019-01-06
esp splay acm contain queue boa ted rate namespace
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.
鏈接:https://ac.nowcoder.com/acm/contest/338/B
來源:牛客網
題目描述
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 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 buildingNext 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.示例1
輸入
復制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板子題
#include <iostream> #include <stdio.h> #include <queue> #include<cstring> using namespace std; typedef pair<int, int> P; #define max_n 102 #define max_m 102 #define inf 1000000 int N,M; int map[max_n][max_m]; int direct[max_n][max_m]; int sx,sy; int ans; int dx[4]= {1,0,-1,0},dy[4]= {0,1,0,-1}; int bfs(int sx,int sy,int gx,int gy) { int nx,ny; queue<P> Q; memset(direct, inf, sizeof(direct)); Q.push(P(sx,sy)); direct[sx][sy]=0; while (Q.size()) { P q=Q.front(); Q.pop(); if (q.first==gx&&q.second==gy) break; else { for (int i=0; i<=3; i++) { nx=q.first+dx[i]; ny=q.second+dy[i]; if (nx<0||nx>N||ny<0||ny>M||map[nx][ny]==1||direct[nx][ny]<inf) continue; else { direct[nx][ny]=direct[q.first][q.second]+1; Q.push(P(nx,ny)); } } } } return direct[gx][gy]; } int main() { int gx,gy; scanf("%d %d",&N,&M); scanf("%d %d",&gx,&gy); for (int i=0; i<N; i++) for(int j = 0; j<M; j++) { scanf("%d",&map[i][j]); } ans=bfs(0, 0, gx-1, gy-1); printf("%d\n",ans); return 0; }View Code
B bearBaby loves sleeping