您的位置:首页 > 其它

COJ 1046 追杀

2012-07-03 22:17 357 查看
马可以从任意位置出发,走遍整个棋盘;

先用 bfs 求出马到达每个位置的最短时间 Ti,然后模拟将的移动,当将移动的时间 Tk 满足 Tk>=Ti 且Tk-Ti为偶数时相遇(马可以在两个位置徘徊一会等待将的到来);

# include <stdio.h>
# include <string.h>
const int dir[][2] = {{1,2}, {2,1}, {-1,2}, {1,-2}, {-2,1}, {2,-1}, {-1,-2}, {-2,-1}};
int nx, ny, kx, ky;
char vis[9][8], dis[9][8];
void bfs(void)
{
char Q[85][2];
int front, rear, i, cx, cy, x, y;
memset(vis, 0, sizeof(vis));
vis[nx][ny] = 1;
dis[nx][ny] = 0;
Q[1][0] = nx, Q[1][1] = ny;
front = 1, rear = 2;
while(front < rear)
{
cx = Q[front][0], cy = Q[front][1];
++front;
for( i = 0; i < 8; ++i )
{
x = cx + dir[i][0], y = cy + dir[i][1];
if(0<=x&&x<=8 && 0<=y&&y<=7 && !vis[x][y])
{
Q[rear][0] = x, Q[rear][1] = y;
++rear;
dis[x][y] = dis[cx][cy] + 1;
vis[x][y] = 1;
}
}
}
}

int search(void)
{
int t, dx, dy;

t = 0;
dx = 1, dy = 1;
while(1)
{
if(t>=dis[kx][ky] && (t-dis[kx][ky])%2==0) return t;
++t;
if(0==kx && -1==dx) dx = 1;  // 向右
if(8==kx && 1==dx) dx = -1;  // 向左
if(0==ky && -1==dy) dy = 1;  // 向下
if(7==ky && 1==dy) dy = -1;  // 向上
kx += dx, ky += dy;
}
}

int main()
{
while(~scanf("%d%d%d%d", &nx,&ny,&kx,&ky))
{
bfs();
printf("%d\n", search());
}
}


//
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: