温习bfs
题目链接
#include <stdio.h>
#include <queue>
#include <string.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
//int n;
int Map[8][8];
int ex,ey,sx,sy,r,c;
int dir[8][2]={{-1,0},{1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};
struct Node
{
int x,y,step;
};
int check(int x,int y)
{
if(x>=0&&x<8&&y>=0&&y<8&&Map[x][y]==0)
return 1;
else
return 0;
}
int BFS(int x, int y)
{
// if (sx == ex && sy == ey)
// {
// printf("0\n");
// return;
// }
Node temp;
Node next;
queue<Node> Queue;
temp.x = x;
temp.y = y;
temp.step=0;
Map[x][y]=1;
Queue.push(temp);
while(!Queue.empty())
{
temp=Queue.front();
Queue.pop();
if(temp.x==ex&&temp.y==ey)
{
//printf("Case 1: 7%d\n",temp.step);
return temp.step;
}
else
for (int i=0; i<8;i++)
{
next.x=temp.x+dir[i][0];
next.y=temp.y+dir[i][1];
if(check(next.x,next.y)==1)
{
if(next.x==r&&next.y==c)
continue;
next.step=temp.step+1;
Map[next.x][next.y]=1;
Queue.push(next);
}
}
}
return -1;
}
int main()
{
int t=0;
int ans;
//int ex,ey,sx,sy;
// scanf("%d",&t);
while(~scanf("%d %d %d %d %d %d",&sx,&sy,&ex,&ey,&r,&c))
{
t++;
memset(Map,0,sizeof(Map));
//scanf("%d",&n);
//scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
sx--;sy--;ex--;ey--;r--;c--;
ans=BFS(sx,sy);
printf("Case %d: %d\n",t,ans);
}
return 0;
}