1. 程式人生 > >A - 移動的騎士

A - 移動的騎士

A - 移動的騎士

Time Limit: 1000/1000MS (C++/Others) Memory Limit: 65536/65536KB (C++/Others)

Problem Description

Somurolov先生是一個國際象棋高手,他聲稱在棋盤上將騎士棋子從一點移動到另外一點,沒有人比他快,你敢挑戰他嗎?
你的任務是程式設計計算出將一個騎士棋子從一點移動到另外一點,最少需要移動的步數。顯而易見,這樣你就有贏得Somurolov先生的機會。國際象棋中的騎士在棋盤上可移動的範圍如下圖:

Input

首先輸入測試樣例的個數n。接下來是n組輸入資料,每組測試資料由三行整陣列成:第一行是棋盤的邊長l (4 <= l <= 300),整個棋盤的面積也就是 l*l;第二行和第三行分別是騎士棋子的初始位置和目標位置,表示為整數對形式{0, …, l-1}*{0, …, l-1}。保證棋子的初始和目標位置是棋盤上的合法位置。

Output

對於每一個輸入的測試樣例,請你算出騎士從初始位置移動到目標位置最小移動步數。如果初始位置和目標位置相同,那麼騎士移動的距離就是0。最後單獨一行輸出所求距離。

Sample Input

3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1

Sample Output

5
28
0




#include<cstdio>
#include<cstring>
#include<queue>
using
namespace std; const int maxn = 305; bool mp[maxn][maxn]; // 表示當前點是否被走過 int sx, sy, tx, ty, l; // s表示初始座標,t表示目標位置 int tox[] = {1, 2, 2, 1, -1, -2, -2, -1}; int toy[] = {2, 1, -1, -2, -2, -1, 1, 2}; // 通過下標關聯,表示馬的八個走向 struct Node { // 結構體,表示當前點的座標和到達步數 int x, y, s; }; bool judge(Node n){ //
用於判斷一個座標(x, y)是否在圖內,並且沒有被走過 if(n.x >=0 && n.x < l && n.y >= 0 && n.y < l && !mp[n.x][n.y]) return true; return false; } int bfs(){ Node now, nxt; queue<Node > q; now.x = sx; now.y = sy; now.s = 0; // 起始點的初始化 q.push(now); // 將起始點加入佇列 mp[now.x][now.y] = true; // 起始點已經走過了 while(!q.empty()){ now = q.front(); q.pop(); if(now.x == tx && now.y == ty) return now.s; //到達目標點 for(int i=0; i<8; i++){ // 列舉馬的八種走法 nxt.x = now.x + tox[i]; nxt.y = now.y + toy[i]; nxt.s = now.s + 1; if(judge(nxt)){ // 下一個位置在圖內且可以走 q.push(nxt); // 加入佇列 mp[nxt.x][nxt.y] = true; } } } return -1; } int main() { int n; scanf("%d", &n); while(n--){ memset(mp, false, sizeof(mp)); scanf("%d", &l); scanf("%d%d", &sx, &sy); scanf("%d%d", &tx, &ty); int ans = bfs(); printf("%d\n", ans); } return 0; }