1 Knight Moves

Problem F- Knight Moves

题目来源:https://vjudge.net/contest/207868#problem/F

Problem description:

题意概括:中国象棋中的‘马’走日字格,从一个点到另一个点最短需要多少步。

 

解题思路:利用广度优先搜索解这道题

AC代码:

#include<stdio.h>
#include<string.h>
 
struct note
{
      int x;
      int y;
      int s;
}; 
 
int main(void)
{
      struct note que[70];
      char f, c;
      int b, d;
      int a[10][10], book[10][10];
      int next[8][2] = {{-1, -2}, {-1, 2},{1,-2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1},{2, 1}};
      int head, tail;
      int flag, i, tx, ty;
      while(scanf("%c%d %c%d", &f,&b, &c, &d)!= EOF)
      {
            memset(a, 0, sizeof(a));
            memset(book, 0, sizeof(book));
            head = 1;
            tail = 1;
            que[tail].x = b;
            que[tail].y = f - 'a' + 1;
            que[tail].s = 0;
            tail ++;
            book[b][f - 'a' + 1] = 1;
            flag = 0;
            while(head < tail)
            {
                  if(f == c && b == d)
                  {
                        que[tail - 1].s = 0;
                        break;
                  }
                  for(i = 0; i <= 7; i ++)
                  {
                        tx = que[head].x +next[i][0];
                        ty = que[head].y +next[i][1];
                        if(tx < 1 || tx >8 || ty < 1 || ty > 8)
                        {
                              continue;
                        }
                        if(book[tx][ty] == 0)
                        {
                              book[tx][ty] = 1;
                              que[tail].x = tx;
                              que[tail].y = ty;
                              que[tail].s =que[head].s + 1;
                              tail ++;
                        }
                        if(tx == d && ty+ 'a' - 1 == c)
                        {
                              flag = 1;
                              break;
                        }
                  }
                  if(flag == 1)
                  {
                        break;
                  }
                  head ++;
            }
            printf("To get from %c%d to%c%d takes %d knight moves.\n", f, b, c, d, que[tail - 1].s);
            getchar();
      }
       
      return 0;
}

错误原因:忘记了输入%c时要吃掉回车。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值