Knight Moves hdu1372 bfs

/*
一开始题目没有看懂,原来是象棋中的跳马问题你不是喜欢下棋的么?可是为何。。。纠结
这是我第一自己独立写的bfs, 在通过调试,终于改了自己犯的低级的毛病(标记为@的地方)
*/
#include<iostream>//2374758 2010-04-23 14:41:15 Accepted 1372 46MS 292K 1189 B C++ 悔惜晟
#include<queue>
#include<cstdio>
using namespace std;

int map[10][10];
bool hash[10][10];
int si, sj;
int ei, ej;
char str1[5];
char str2[5];
int dir[8][2] = { {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2} };
struct Node
{
 int x;
 int y;
 int t;
};
int bfs(int i, int j)
{
 Node P , N;
 int k;
 N.x = i; N.y = j; N.t = 0;
 queue<Node> q;
 q.push(N);
 hash[i][j] = false;
 while(!q.empty())
 {
  N = q.front();
  q.pop();
  if(N.x == ei && N.y == ej)
  {
   cout<<"To get from "<<str1<<" to "<<str2<<" takes "<<N.t<<" knight moves."<<endl;
   //cout<<N.t<<endl;
   break;
  }
  for(k = 0; k < 8; k++)
  {
   int tx = N.x + dir[k][0];
   int ty = N.y + dir[k][1];
   if( tx >= 1 && tx <= 8 && ty >= 1 && ty <= 8 && hash[tx][ty] )//还有这里以开始也标记错误,不小心写成 !hash[tx][ty]
   {
    P.x = tx;
    P.y = ty;
    P.t = N.t + 1;
    q.push(P);
    hash[P.x][P.y] = false;

   }
   
  }
 }
 return 1;
 
}
int  main()
{
 while(scanf("%s%s", str1, str2) != EOF)
 {
  si = str1[1]  - '0';
  sj = str1[0]  - 96;//@一开始这里写成sj = str1[0]  -'0'- 96; 调试之后发现 sj的值变成负数
  ei = str2[1]  - '0';
  ej = str2[0]  - 96;

  memset(hash, true, sizeof(hash));
  bfs(si, sj);
  //cout<<endl;
 }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值