POJ 1915 Knight Moves bfs
这题一般bfs都能过,尝试写了个双向bfs
单向bfs, 450+ms, 双向300+ms
#include <iostream> #include <queue> #include <memory.h> using namespace std; struct coordinate { int x, y; int step; }; int dir[8][2] = {{1, 2}, {1, -2}, {-1, 2}, {-1, -2 }, {2,1}, {2, -1}, {-2, 1}, {-2, -1}}; int isvisit[301][301]; int step[301][301]; coordinate goal, start; int board; void bfs(); int main() { int n; cin >> n; while (n--) { memset(isvisit, 0, sizeof(isvisit)); memset(step, 0, sizeof(step)); cin >> board; cin >> start.x >> start.y; start.step = 0; isvisit[start.x][start.y] = 1; cin >> goal.x >> goal.y; goal.step = 0; isvisit[goal.x][goal.y] = 2; bfs(); } return 0; } void bfs() { coordinate p, next; queue<coordinate> Q1; queue<coordinate> Q2; p = start; Q1.push(p); p = goal; Q2.push(goal); while (! Q1.empty()) { p = Q1.front(); Q1.pop(); if (p.x == goal.x && p.y == goal.y) { cout << p.step << endl; return; } for (int i = 0; i < 8; i++) { next.x = p.x + dir[i][0]; next.y = p.y + dir[i][1]; next.step = p.step + 1; if (next.x >= 0 && next.x < board && next.y >= 0 && next.y < board) { if (isvisit[next.x][next.y] == 0) { isvisit[next.x][next.y] = 1; step[next.x][next.y] = next.step; Q1.push(next); } else if (isvisit[next.x][next.y] == 2) { cout << next.step + step[next.x][next.y] << endl; return; } } } p = Q2.front(); Q2.pop(); for (int i = 0; i < 8; i++) { next.x = p.x + dir[i][0]; next.y = p.y + dir[i][1]; next.step = p.step + 1; if (next.x >= 0 && next.x < board && next.y >= 0 && next.y < board) { if (isvisit[next.x][next.y] == 0) { isvisit[next.x][next.y] = 2; step[next.x][next.y] = next.step; Q2.push(next); } else if (isvisit[next.x][next.y] == 1) { cout << next.step + step[next.x][next.y] << endl; return; } } } } }