c ++ breadth-first search (broad search)

c ++ bfs basic application

Knight Moves

Title Description

Bessie and her cousin playing a simplified version of chess. As illustrated the board:

Bessie and a cousin each piece. Pieces each shift step, and the pieces only to move in eight directions as shown in FIG. Rules of the game is very simple, two people will be required from the starting point to the ending point pawn, who spend the least number of steps come to the end from the beginning, is the winner.
In order to ensure win cousin, Bessie want every time to calculate the minimum number of steps, you can help her?

Entry

Enter the start and end points, separated by a space. (Ensure that the starting point must be able to come to an end)

Export

Enter the minimum number of steps.

Sample input

a1 b2

Sample Output

4

On the code:

AC Code

#include <bits/stdc++.h>
using namespace std;
struct Point
{
    int x,y,step;
};
Point q[1000000],s,t;//t是终点,s是起点 
int dx[8]={1,-1,1,-1,2,2,-2,-2};//dx[] + dy[] 代表Knight走的8个方向可达的点 
int dy[8]={2,2,-2,-2,1,-1,1,-1};
int f=1,e=0;
int main()
{
    char ca,cb,cc,cd;
    scanf("%c%c %c%c",&ca,&cb,&cc,&cd);//输入 
    s.x=ca-'a'+1,s.y=cb-'1'+1;s.step=0;//把a转换成数字1 把字符1转换成数字1 
    t.x=cc-'a'+1,t.y=cd-'1'+1;t.step = 0;//把b转换成数字2 把字符2转换成数字2 
    if(s.x==t.x&&s.y==t.y)//如果起点等于终点,就直接退出 
    {
        printf("0\n");
        return 0;
    }
    e++;//队列入队时候的下标
     
    q[e]=s;//q就是队列 把所有待查找的元素放在q队列里面 
    while(f<=e)//出队的下标不能大于入队时候的下标 
    {
        Point u=q[f];//f是队列出队时候的下标      //* u是在队列中选定的骑士 *//
        for(int i=0;i<8;i++)//for循环为了能 加上dx[] 和dy[] 
        {
            Point v;//v是有效的骑士 
            v.x = u.x + dx[i],v.y = u.y + dy[i],v.step=u.step + 1;//把选定的位置向8个方向扩展(一次) 
            if(v.x<1||v.x>8||v.y<1||v.y>8)continue;//如果这个骑士的位置不在棋盘上,则丢弃 
            if(t.x==v.x&&t.y==v.y)//找到了终点 
            {
                printf("%d\n",v.step);//输出步数 
                return 0;
            }
            e++;// 把入队下标 + 1 
            q[e]=v;//  入队 
        }
        f++;//出队下标 + 1 
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/LJA001162/p/11183692.html