POJ 1915 BFS-Knight Moves

来源:互联网 发布:使命召唤14数据不兼容 编辑:程序博客网 时间:2024/05/20 01:34

Description
Background
Mr Somurolov, fabulous chess-gamer indeed, asserts that no one else but him can move 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 needed for a knight to reach one point from another, so that you have the chance to be faster than Somurolov.
For people not familiar with chess, the possible knight moves are shown in Figure 1.
这里写图片描述

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

Output
For each scenario of the input you have to calculate the minimal amount of knight moves which are necessary to move from the starting point to the ending point. If starting point and ending point are equal,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

*题意:*


国际象棋中的骑士,可以走如上面走的八个方向,即马走日,求骑士从一个点出发到另一个点最小的步数。


*题解:*


本题是一个较为简单的深度优先搜索问题,从起点开始向八个方向进行搜索,用队列保存这些点的坐标,当第一次搜索到目标点的时候就可以停止,可以知道此时目标点是最小的点,可以用一个数组记录每一个点是否被访问过,同时保存到达每一个点的步数。


#include <iostream>#include <queue>#include <string.h>#define MAXN 300+5using namespace std;const int dx[] = {-2,-2,-1,-1,1,1,2,2};const int dy[] = {1,-1,2,-2,2,-2,1,-1};int vis[MAXN][MAXN];queue<int> q;int l;int x0,y0;int x1,y1;void bfs(){    while(!q.empty()) q.pop();    q.push(x0*l+y0);    while(!q.empty())    {        int u = q.front();        q.pop();        int cx = u/l;        int cy = u%l;        if(cx == x1 && cy == y1)        {            cout << vis[cx][cy] << endl;            return;        }        for(int k = 0; k < 8; k++)        {            int nx = cx + dx[k];            int ny = cy + dy[k];            if(nx >= 0 && nx < l && ny >= 0 && ny < l && vis[nx][ny] == 0)            {                vis[nx][ny] = vis[cx][cy] + 1;                q.push(nx*l+ny);            }        }    }}int main(){    int t;    cin >> t;    while(t--)    {        cin >> l;        cin >> x0 >> y0;        cin >> x1 >> y1;        if(x0 == x1 && y0 == y1)        {            cout << 0 << endl;            continue;        }        memset(vis, 0, sizeof(vis));        bfs();    }    return 0;}
0 0
原创粉丝点击