摘要:BFS, 注意
1。坐标(x,y)对应数组的位置是array[y][x]
2。每个测试数据前要清空队列(白耗了好几个小时,汗……)
#include <iostream>
#include <queue>
using namespace std;
typedef struct Node{
int x;
int y;
int dist;
}Node;
queue<Node> q;
Node start;
Node finish;
int length = 0;
const int size = 300;
const int offset_num = 8;
int offset_x[offset_num+1] = {0};
int offset_y[offset_num+1] = {0};
int graph[size+1][size+1] = {0};
void initOffset()
{
offset_x[1] = -2;
offset_x[2] = -1;
offset_x[3] = 1;
offset_x[4] = 2;
offset_x[5] = 2;
offset_x[6] = 1;
offset_x[7] = -1;
offset_x[8] = -2;
offset_y[1] = -1;
offset_y[2] = -2;
offset_y[3] = -2;
offset_y[4] = -1;
offset_y[5] = 1;
offset_y[6] = 2;
offset_y[7] = 2;
offset_y[8] = 1;
}
bool checkOffset(int i, Node current)
{
int x = current.x + offset_x[i];
int y = current.y + offset_y[i];
if(x<0 || x>=length || y<0 || y>=length){
return false;
}
if(graph[y][x] > 0){
return false;
}
return true;
}
void BFS()
{
if(start.x==finish.x && start.y==finish.y){
finish.dist = 0;
return;
}
Node current = start;
while(true){
bool find = false;
for(int i=1; i<=offset_num; i++){
if( checkOffset(i, current) ){
Node next;
next.x = current.x+offset_x[i];
next.y = current.y+offset_y[i];
next.dist = current.dist + 1;
if(next.x==finish.x && next.y==finish.y){
find = true;
finish.dist = next.dist;
break;
}
q.push(next);
graph[next.y][next.x] = next.dist;
}
}
if( find ){
break;
}
if( q.empty() ){
break;
}
current = q.front();
q.pop();
}
}
int main()
{
int n = 0;
cin >> n;
initOffset();
while( n > 0 ){
cin >> length;
cin >> start.x >> start.y >> finish.x >> finish.y;
start.dist = finish.dist = 0;
for(int i=0; i<length; i++){
for(int j=0; j<length; j++){
graph[i][j] = 0;
}
}
while( !q.empty() ){
q.pop();
}
BFS();
cout << finish.dist << endl;
n--;
}
}