Knight Moves hdu1372 bfs

來源:互聯網
上載者:User

/*
一開始題目沒有看懂,原來是象棋中的跳馬問題你不是喜歡下棋的嗎?可是為何。。。糾結
這是我第一自己獨立寫的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;
 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.