Mud Puddles 简单BFS

Mud Puddles
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 3445   Accepted: 1965

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 (XY) (-500 ≤ X ≤ 500; -500 ≤ Y ≤ 500). He can see all N (1 ≤ N ≤ 10,000) puddles of mud, located at points (AiBi) (-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: XY, 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

Source

代码分析:

就一点,所以的数都加500

#include<iostream>  
#include<cstdio>  
#include<cstring>  
#include<cmath>  
#include<algorithm>  
#include<string>  
#include<cstdlib>  
#include<queue>  
#include<vector>  
#define INF 0x7fffffff  
#define PI acos(-1.0)  

#define MOD 2520  
#define E 1e-12 
using namespace std;
#define N  1010
int flag[N][N];
int n,fx,fy;
int dx[4]={0,0,1,-1},
    dy[4]={1,-1,0,0};
struct node
{
	int x,y;
	int step;
}a,b;
int bfs()
{
	 a.x=500;
	 a.y=500;
	 a.step=0;
	 flag[a.x][a.y]=1;
	 queue<node>q;
	 while(!q.empty())
	  q.pop();
      q.push(a);
      while(!q.empty())
	  {  
	  	 a=q.front();
	  	 q.pop();
	  	 for(int i=0;i<=3;i++)
		 {
		 b.x=a.x+dx[i];
		 b.y=a.y+dy[i];
		 	b.step=a.step+1;
		 if(b.x>=0&&b.x<=1000&&b.y>=0&&b.y<=1000&&!flag[b.x][b.y])
		  {
		
			q.push(b);
			if(b.x==fx&&b.y==fy)
			{
				cout<<b.step<<endl;
				return 0;
			}
		 	  flag[b.x][b.y]=1;
	      }
		 }
	  }
}
int main()
{

    while(scanf("%d%d%d",&fx,&fy,&n)!=EOF)
    {
    	memset(flag,0,sizeof(flag));   
    	 fx+=500;
    	 fy+=500;
        for(int i=1;i<=n;i++)
        {
        	int f,e;
            scanf("%d%d",&f,&e);
			{
               	flag[f+500][e+500]=1;
			}           
        }
		bfs();
    }
        return 0;
}

猜你喜欢

转载自blog.csdn.net/sdz20172133/article/details/80836964
今日推荐