UVA 439 Knight Moves

来源:互联网 发布:c语言函数编程心得体会 编辑:程序博客网 时间:2024/05/29 11:43

UVA 439 Knight Moves

题目

中文简单翻译就是国际象棋规定马的起点终点,算出最短路径。

分析

就是简单的广度优先遍历BFS,用队列,格式如下

queue.push(root)while(!queue){    var buf = queue.front();    //处理这个节点    for(...)    {        queue.push();       }    queue.pop();}

代码

#include<stdio.h>#include<iostream>#include<string.h>#include<queue>using namespace std;int movex[8]={-2,-2,-1,-1,1,1,2,2};int movey[8]={-1,1,2,-2,-2,2,1,-1};int map[9][9];class point{    public :        int x;        int y;        int count = 0;  };int bfs(point ,point);int main(){    char x1,x2,y1,y2;    while (cin>>x1>>y1>>x2>>y2)    {        point start ;        point end ;        start.x=x1-'a'+1;        start.y=y1-'0';        end.x=x2-'a'+1;        end.y=y2-'0';        printf("To get from %c%c to %c%c takes %d knight moves.\n",x1,y1,x2,y2,bfs(start,end));    }}int bfs(point start,point end){    if(start.x==end.x&&start.y==end.y) return 0;    queue<point> q;    q.push(start);    while(!q.empty())    {        point buf_q=q.front();        for(int i=0;i<8;i++){            int x=buf_q.x+movex[i];            int y=buf_q.y+movey[i];            if(x>0&&x<9&&y>0&&y<9)            {                if(x==end.x&&y==end.y)return buf_q.count+1;                else{                    point input;                    input.x=x;                    input.y=y;                    input.count=buf_q.count+1;                    q.push(input);                }            }        }        q.pop();    }}
0 0
原创粉丝点击