POJ-2243

#include <stdio.h>
#include <string.h>

int chessboard[8][8];
char s1[2], s2[2];
int queue[100], top, rear;
int position[8][2] = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}};

void bfs(void)
{
     int i, x, y, temp1, temp2;
     do {
        x = queue[top]/10;
        y = queue[top]%10;
        top++;
        top %= 100;
        for (i = 0; i < 8; i++) {
            temp1 = x+position[i][0];
            temp2 = y+position[i][1];
            if (temp1 >=0 && temp1 < 8 && temp2 >= 0 && temp2 < 8 && chessboard[temp1][temp2] == -1) {
               ++rear;
               rear %= 100;
               queue[rear] = temp1*10 + temp2;
			   chessboard[temp1][temp2] = x*10+y;
               if (temp1 == s2[0]-'a' && temp2 == s2[1]-'1')
                  return;
            }
        }
     }while (top != rear);
}

int main()
{
    int num, n, i, j;
    while (scanf("%s%s", s1, s2) == 2) {
          top =rear = 0;
          for (i = 0; i < 8; i++)
              for (j = 0; j < 8; j++)
                  chessboard[i][j] = -1;
          chessboard[s1[0]-'a'][s1[1]-'1'] = queue[rear] = (s1[0]-'a')*10 + s1[1]-'1';
          num = 0;
          if (s1[0] != s2[0] || s1[1] != s2[1]) {
             bfs();
             num = 1;
          }
          i = s2[0]-'a';
          j = s2[1]-'1';
          for (; chessboard[i][j] != (s1[0]-'a')*10 + s1[1]-'1'; num++) {
			  n = chessboard[i][j];
              i = n/10;
              j = n%10;
          }
          printf("To get from %s to %s takes %d knight moves.\n", s1, s2, num);        
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值