Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 3690 | Accepted: 2046 |
Description
Farmer John is leaving his house promptly at 6 AM for his daily milking of Bessie. However, the previous evening saw a heavy rain, and the fields are quite muddy. FJ starts at the point (0, 0) in the coordinate plane and heads toward Bessie who is located at (X, Y) (-500 ≤ X ≤ 500; -500 ≤ Y ≤ 500). He can see all N (1 ≤ N ≤ 10,000) puddles of mud, located at points (Ai, Bi) (-500 ≤ Ai ≤ 500; -500 ≤ Bi ≤ 500) on the field. Each puddle occupies only the point it is on.
Having just bought new boots, Farmer John absolutely does not want to dirty them by stepping in a puddle, but he also wants to get to Bessie as quickly as possible. He's already late because he had to count all the puddles. If Farmer John can only travel parallel to the axes and turn at points with integer coordinates, what is the shortest distance he must travel to reach Bessie and keep his boots clean? There will always be a path without mud that Farmer John can take to reach Bessie.
Input
* Line 1: Three space-separate integers: X, Y, and N.
* Lines 2..N+1: Line i+1 contains two space-separated integers: Ai and Bi
Output
* Line 1: The minimum distance that Farmer John has to travel to reach Bessie without stepping in mud.
Sample Input
1 2 7 0 2 -1 3 3 1 1 1 4 2 -1 1 2 2
Sample Output
11
题意:深搜,机器人只能朝x轴或y轴平行方向走,避开陷阱到达终点
#include<iostream>
#include<queue>
using namespace std;
int endx,endy;
int n;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
int map[10010][10010];
int vis[10010][10010];
int step;
struct Node{
int x,y;
int step;
};
queue<Node>q;
void bfs(){
Node now;
now.x=500;
now.y=500;
now.step=0;
q.push(now);
vis[500][500]=1;
while(!q.empty()){
now=q.front();
if(now.x==endx&&now.y==endy){
step=now.step;
return ;
}
vis[now.x][now.y]=1;
q.pop();
for(int i=0;i<4;i++){
if(!map[now.x+dx[i]][now.y+dy[i]]&&!vis[now.x+dx[i]][now.y+dy[i]])
{
Node next;
next.x=now.x+dx[i];
next.y=now.y+dy[i];
next.step=now.step+1;
vis[next.x][next.y]=1;
q.push(next);
}
}
}
}
int main(){
cin>>endx>>endy>>n;
endx+=500;
endy+=500;
for(int i=0;i<n;i++){
int a,b;
cin>>a>>b;
map[a+500][b+500]=1;
}
bfs();
cout<<step<<endl;
return 0;