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时要吃掉回车。

posted @ 2018-01-23 17:27  moonlight987  阅读(115)  评论(0编辑  收藏  举报