zju 1091 Knight Moves

  这是一道bfs的习题,比较经典,以前也没做过bfs的题,第一次做,记录下思路。
  首先,应该弄明白的是BFS要通过队列来实现,我向来不喜欢做题时自己再将什么声明队列,出队列,入队列的函数给写出来,感觉有点麻烦。这次我才发现有queue、stack的这种头文件,可以直接使用。第一步将起点位置加入队列,如果当队列为空还没有访问到目标位置就代表访问不到目标位置了。
  其次,这道题求的是最少的步数,一旦搜索到目标位置,就立马停止搜索,输出步数。那么这个步数怎么来算呢??如何避免访问已经访问过的位置呢??这里建立一个二维数组,存放每一个位置的状态,-1表示没有访问过,其他的值代表访问这个位置的时候已经走过的步数。比如说,<3,3>这个点状态是4,那就代表第四步的时候能访问到<3,3>,因为<3,3>下一步可以走到<4,5>,那么<4,5>的状态也就是5了,代表第5步可以访问到<4,5>。当第一次访问到目标位置时,目标位置的状态就是需要走过的步数。
  下面是这道题的代码,代码很简洁,欢迎大家讨论。我是菜鸟。。

 1 #include<iostream> 
 2 #include<cstring>   
 3 #include<queue> 
 4 using namespace std; 
 5 class Cordinate  
 6 {public:int x,y;};  
 7 using namespace std;  
 8 int dir[8][2]={1,2,1,-2,2,1,2,-1,-1,2,-1,-2,-2,1,-2,-1},chess[10][10];  
 9 bool legal(Cordinate po)  
10 {if(po.x>=1&&po.x<=8&&po.y>=1&&po.y<=8)return true;return false;}  
11 int main()  
12 {   
13        char a[3],b[3];Cordinate po,pos;int i;  
14        while(cin>>a>>b)  
15        {  
16             queue<Cordinate>q;  
17             memset(chess,-1,sizeof(chess));  
18             pos.x=a[0]-'a'+1;pos.y=a[1]-'0';  
19             chess[pos.x][pos.y]=0;  
20            q.push(pos);  
21             while(!q.empty()&&chess[b[0]-'a'+1][b[1]-'0']==-1)  
22             {  
23                po=q.front();q.pop();  
24                 for(i=0;i<8;i++)  
25                 {  
26                     pos.x=dir[i][0]+po.x;pos.y=dir[i][1]+po.y;  
27                     if(legal(pos)&&chess[pos.x][pos.y]==-1) 
28                     {q.push(pos);chess[pos.x][pos.y]=chess[po.x][po.y]+1;}  
29                 }  
30             }  
31             cout<<"To get from "<<a<<" to "<<b<<" takes "<<chess[b[0]-'a'+1][b[1]-'0']<<" knight moves."<<endl;  
32        }  
33         return 0;  
34 }

 

posted @ 2012-11-18 14:07  简单地快乐  阅读(463)  评论(0编辑  收藏  举报