poj1915 简单bfs

本文深入探讨了跳棋中马子从一个位置跳到另一个位置的最短路径问题,通过应用广度优先搜索(BFS)算法,为读者揭示了解决该问题的方法,并提供了AC代码示例。通过分析输入输出样例,读者能够理解如何计算最小移动次数以战胜国际跳棋高手Somurolov。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Background
Mr Somurolov, fabulous chess-gamer indeed, asserts that no one else but him canmove knights from one position to another so fast. Can you beat him?
The Problem
Your task is to write a program to calculate the minimum number of moves neededfor a knight to reach one point from another, so that you have the chance to befaster than Somurolov.
For people not familiar with chess, the possible knight moves are shown inFigure 1.

 

Input

The input begins with the number n of scenarios on asingle line by itself.
Next follow n scenarios. Each scenario consists of three lines containinginteger numbers. The first line specifies the length l of a side of the chessboard (4 <= l <= 300). The entire board has size l * l. The second andthird line contain pair of integers {0, ..., l-1}*{0, ..., l-1} specifying thestarting and ending position of the knight on the board. The integers areseparated by a single blank. You can assume that the positions are validpositions on the chess board of that scenario.

Output

For each scenario of the input you have to calculate theminimal amount of knight moves which are necessary to move from the startingpoint to the ending point. If starting point and ending point areequal,distance is zero. The distance must be written on a single line.

Sample Input

3

8

0 0

7 0

100

0 0

30 50

10

1 1

1 1

Sample Output

5

28

0

 

 

 

 

题目分析:求象棋中,“马”从一个点跳到另一个点的最少步数。用bfs求最短路径。

 

 

AC代码:

#include <iostream>

#include <cstring>

#include <cstdio>

#include <queue>

 

using namespace std;

bool vis[310][310];//标记数组

int n;

intdx[]={-1,-2,-2,-1,1,2,2,1},dy[]={2,1,-1,-2,-2,-1,1,2};//方向数组

struct P{//点类

   int x,y;

};

struct Node{//队元素

    Px;

   int step;

};

int bfs(P a,P b){

   memset(vis,false,sizeof(vis));

   vis[a.x][a.y]=true;

   Node now,next;

   now.x=a;now.step=0;

   queue<Node> q;//用队列实现bfs

   q.push(now);

   while(!q.empty()){

       now=q.front();q.pop();

       if(now.x.x==b.x && now.x.y==b.y){

            return now.step;

       }

       for(int i=0;i<8;++i){

           int xx=next.x.x=now.x.x+dx[i],yy=next.x.y=now.x.y+dy[i];

           next.step=now.step+1;

           if(xx>=0 && xx<n && yy>=0 && yy<n&& !vis[xx][yy]){

                vis[xx][yy]=true;

                q.push(next);

           }

       }

    }

   return 0;

}

int main()

{

   int t;scanf("%d",&t);

   while(t--){

       scanf("%d",&n);

       P a,b;

       scanf("%d%d%d%d",&a.x,&a.y,&b.x,&b.y);

       int ans=bfs(a,b);

       printf("%d\n",ans);

    }

   return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值