Problem A: Yuchang and Zixiang ‘s maze
Time Limit: 2 Sec Memory Limit: 128 MB
Submit: 907 Solved: 160
[Submit][Status][Web Board]
Description
One day , Yuchang and Zixiang go out of school to find some thing interesting . But both of them is LuChi , so the miss the way easily .
“Where am I ? who am I ?” Yuchang says . “Who attack you? You must want to say .” Zixiang adds . “Don’t say that , how we get out there ? I want my mom 555555……” Yuchang started crying . Zixiang become very panic . He doesn’t know how to get out there.
Now , they find they are in a N*M maze , they are at the (a,b) point , they know they want to go to the point (c,d) , they want to finish as soon as possible, so , could you help them ?
Same as other maze , there are some point has boom , means they can’t get the point . Give you N,M and Num (the number of points that have booms . ) , then , Num lines contains pairs (x,y) means point (x,y) have booms . then , one line contains a , b , c , d ,the begin and end point .
They can mov forward , back , left and right . And every move cost 1 second . Calculate how many seconds they need to get to the finish point .
Input
The first line contains tow numbers N,M (0 < x,y < 1000)means the size of the maze.
The second line contains a number Num (0 < N < X*Y), means the number of points which have booms .
Then next N lines each contain two numbers , xi,yi , means (xi,yi) has a boom .
Output
One line , contains one number , the time they cost .
If they can’t get to the finish point , output -1 .
Sample Input
1000 1000 4
5 5
5 7
4 6
6 6
1 1 5 6
Sample Output
-1
用DFS直接炸了,所以用BFS
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
struct mp{
int x,y;
}a,b;
int vx[4]={0,0,1,-1},vy[4]={1,-1,0,0};//方向向量
queue<mp> M;
int dp[1005][1005];int n,m,x1,y1;
int main()
{
int t,x,y,x0,y0;
while(~scanf("%d%d%d",&n,&m,&t))
{
memset(dp,-1,sizeof(dp));
for(int i=0;i<t;i++)
scanf("%d%d",&x,&y),dp[x][y]=1;
scanf("%d%d%d%d",&x0,&y0,&x1,&y1);
a.x=x0,a.y=y0;dp[x0][y0]=0;
M.push(a);
while(!M.empty())
{
a=M.front();M.pop();
for(int j=0;j<4;j++)
if(0<a.x+vx[j]&&a.x+vx[j]<=n&&0<a.y+vy[j]&&a.y+vy[j]<=m&&dp[a.x+vx[j]][a.y+vy[j]]<0)
{
dp[a.x+vx[j]][a.y+vy[j]]=dp[a.x][a.y]+1;
b.x=a.x+vx[j],b.y=a.y+vy[j];
M.push(b);
}
}
printf("%d\n",dp[x1][y1]);
}
return 0;
}
吐槽一下 while(~scanf(“%d%d%d”,&n,&m,&t)) 而用!=EOF 超时了 很不解,而且题目又没说多组输入,一直没想到错在这儿