#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
typedef struct step
{
int x;
int y;
int cost;
}step;
int mark[101][101];
int next[][2] =
{
-2,1,
-1,2,
1,2,
2,1,
-2,-1,
-1,-2,
1,-2,
2,-1
};
int startx,starty,endx,endy,n;
queue<step> que;
int bfs()
{
int i,x,y,cost;
step tmp1,tmp2;
while(!que.empty())
{
tmp1 = que.front();
x = tmp1.x;
y = tmp1.y;
cost = tmp1.cost;
que.pop();
for(i=0; i<8; i++)
{
if(mark[x+next[i][0]][y+next[i][1]] == 0 && x+next[i][0] >= 1 && x+next[i][0] <= n && y+next[i][1] >= 1 && y+next[i][1] <= n)
{
tmp2.x = x+next[i][0];
tmp2.y = y+next[i][1];
tmp2.cost = cost+1;
que.push(tmp2);
mark[tmp2.x][tmp2.y] = 1; //不要忘记标记
if(tmp2.x == endx && tmp2.y == endy)
return tmp2.cost;
}
}
}
return -1;
}
int main()
{
int ans;
step tmp;
while(scanf("%d", &n) != EOF)
{
memset(mark,0,sizeof(mark));
while(!que.empty())
que.pop();
scanf("%d%d%d%d", &startx, &starty, &endx, &endy);
if(startx == endx && starty == endy) //考虑重合的情况
printf("0\n");
else
{
mark[startx][starty] = 1;
tmp.x = startx;
tmp.y = starty;
tmp.cost = 0;
que.push(tmp);
ans = bfs();
printf("%d\n", ans);
}
}
return 0;
}
九度oj-1365:贝多芬第九交响曲
最新推荐文章于 2019-03-11 15:19:27 发布