程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 騎士問題

騎士問題

編輯:C++入門知識

/*騎士問題*/
#include <iostream>
#include <string>
//#include <fstream>
#include <queue>
using namespace std;
#define MAX 12

typedef struct _point
{
        int x;
        int y;
        int dep;
}point;

int map[MAX][MAX];
int p[][2]={{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}};
point start,end;
//fstream fin;

int bfs();
int main()
{  
   //fin.open("2585.txt",ios::in);
   int times=0;
   int b;
   while(cin>>b)
   {
       if(b==-1) break;
       for(int i=0;i<12;i++)
          for(int j=0;j<12;j++)
             map[i][j]=1;
       //周圍圍上柵欄 
       for(int i=2;i<10;i++)
          for(int j=2;j<10;j++)
            map[i][j]=0;
       
       string a;
       for(int i=0;i<b;i++)
       {
                cin>>a;
                map[a[0]-'a'+2][(a[1]-'1')+2]=1;
       } 
  
       cin>>a;
       start.x=a[0]-'a'+2;
       start.y=a[1]-'1'+2;
       start.dep=0;
       
       
       cin>>a;
       end.x=a[0]-'a'+2;
       end.y=a[1]-'1'+2;
       
       int dep=bfs();
       if(dep)
         cout<<"Board "<<++times<<":"<<dep<<" moves"<<endl; 
       else
          cout<<"Board "<<++times<<":not reachable"<<endl;
   }
   system("pause");
   return 0;
}

int bfs()
{
    int dep=0;
    queue<point> Q;
    Q.push(start);
    while(!Q.empty())
    {
          //當前是的dep 
           for(int i=0;i<8;i++)
           {
                   point cur=Q.front();
                   if(map[cur.x+p[i][0]][cur.y+p[i][1]]==0)
                   {
                         if(end.x==cur.x+p[i][0]&&cur.y+p[i][1]==end.y)
                         {
                              end.dep=cur.dep+1;
                              return end.dep;
                         }
                         map[cur.x+p[i][0]][cur.y+p[i][1]]=1;
                         point temp;
                         temp.x=cur.x+p[i][0];
                         temp.y=cur.y+p[i][1];
                         temp.dep=cur.dep+1;
                         Q.push(temp);
                   }
           }
          
           Q.pop();         
    }
    return 0;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved