zoj1091

广度优先搜索

#include <stdio.h>
#include <string.h>
typedef struct
{
 int a, b, cnt;
}POINT;

POINT stack[1000];
int reachable(int x, int y)
{
 if(x >= 0 && x <= 7 && y >= 0 && y <= 7) return 1;
 return 0;
}

int main(void)
{
    char flag[8][8], t1[5], t2[5];
    int dir[8][2] = {1, 2, 1, -2, -1, 2, -1, -2, 2, 1, 2, -1, -2, 1, -2, -1};
    int x1, y1, x2, y2, head, tail, i;
   
    while(scanf("%s%s", t1, t2) != EOF)
    {
  x1 = t1[0] - 'a';
  y1 = t1[1] - '1';
  x2 = t2[0] - 'a';
  y2 = t2[1] - '1';
  memset(flag, 0, sizeof(flag));
  
  head = 0;
  tail = 1;
  stack[head].a = x1;
  stack[head].b = y1;
  stack[head].cnt = 0;
  flag[x1][y1] = 1;
  
  while(head < tail)
  {
   if(stack[head].a == x2 && stack[head].b == y2)
   {
    printf("To get from %s to %s takes %d knight moves.\n", t1, t2, stack[head].cnt);
    break;
   }
   
   for(i = 0; i < 8; i++)
   {
    if(reachable(stack[head].a+dir[i][0], stack[head].b+dir[i][1]) && flag[stack[head].a+dir[i][0]][stack[head].b+dir[i][1]] == 0)
    {
                    flag[stack[head].a+dir[i][0]][stack[head].b+dir[i][1]] = 1;
                    stack[tail].a = stack[head].a+dir[i][0];
     stack[tail].b = stack[head].b+dir[i][1];
     stack[tail].cnt = stack[head].cnt + 1;
     tail ++;
    }
   }
   head ++;
  }
 }
 return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值