题目链接:http://poj.org/problem?id=1915
用两个队列 Q和 P,Q用来储存正向搜索的节点,P用来储存逆向搜索的节点;在地图中进行染色,正向搜索到的节点染色为1,逆向搜索到的节点染色为2,当正向搜索到染色为2的节点时或者逆向搜索到染色为1的节点时表示两者相遇;还要标从起点(或终点)到当前位置所需要的步数,当相遇的时候起点到该点的距离加上重点到该点的距离就是起点到终点的距离。
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int dx[8] = {-1,-2,-2,-1,1,2,2,1};
const int dy[8] = {-2,-1,1,2,2,1,-1,-2};
struct node
{
int x, y;
node() {}
node(int x, int y):x(x), y(y) {}
};
node st, en;
int vis[330][330];
int step[330][330];
int n;
queue<node> Q;
queue<node> P;
bool in(int x, int y)
{
if (x < 0 || x >= n || y < 0 || y >= n)
return false;
return true;
}
int BFS()
{
if (st.x == en.x && st.y == en.y)
return 0;
while (!Q.empty()) Q.pop(); //正向队列
while (!P.empty()) P.