Problem Description
  給定一個m × n (m行, n列)的迷宮,迷宮中有兩個位置,gloria想從迷宮的一個位置走到另外一個位置,當然迷宮中有些地方是空地,gloria可以穿越,有些地方是障礙,她必須繞行,從迷宮的一個位置,只能走到與它相鄰的4個位置中,當然在行走過程中,gloria不能走到迷宮外面去。令人頭痛的是,gloria是個沒什麼方向感的人,因此,她在行走過程中,不能轉太多彎了,否則她會暈倒的。我們假定給定的兩個位置都是空地,初始時,gloria所面向的方向未定,她可以選擇4個方向的任何一個出發,而不算成一次轉彎。gloria能從一個位置走到另外一個位置嗎?
 
Input
  第1行為一個整數t (1 ≤ t ≤ 100),表示測試資料的個數,接下來為t組測試資料,每組測試資料中,
  第1行為兩個整數m, n (1 ≤ m, n ≤ 100),分別表示迷宮的行數和列數,接下來m行,每行包括n個字元,其中字元'.'表示該位置為空地,字元'*'表示該位置為障礙,輸入資料中只有這兩種字元,每組測試資料的最後一行為5個整數k, x1, y1, x2, y2 (1 ≤ k ≤ 10, 1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m),其中k表示gloria最多能轉的彎數,(x1, y1), (x2, y2)表示兩個位置,其中x1,x2對應列,y1, y2對應行。
 
Output
  每組測試資料對應為一行,若gloria能從一個位置走到另外一個位置,輸出“yes”,否則輸出“no”。
 
題目大意:最小轉彎問題。(注意哪些是行哪些是列)
思路:一種O(12nm)的演算法,用dis[i][x][y]代表上一步走的是i方向,現處於(x, y)所需要的最小轉彎數。用兩個佇列BFS,按轉彎數小到大BFS。pre佇列記錄當前用來拓展的結點,step代表目前的轉彎數,同方向的拓展後放到pre佇列後面,轉彎的拓展後放到cur佇列。當pre佇列為空之後,交換cur和pre佇列,step自增1。若step>k結束迴圈。
PS:連連看作業的演算法有著落啦~~
 
程式碼(15MS):
 #include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std; const int MAXN = ; struct Node {
int f, x, y;
Node() {}
Node(int f, int x, int y):
f(f), x(x), y(y) {}
}; int fx[] = {-, , , };
int fy[] = {, , , -}; int dis[][MAXN][MAXN];
char mat[MAXN][MAXN];
int T, n, m;
int k, x1, y1, x2, y2; bool solve() {
memset(dis, 0x3f, sizeof(dis));
queue<Node>* pre = new queue<Node>();
queue<Node>* cur = new queue<Node>();
int step = ;
for(int i = ; i < ; ++i) pre->push(Node(i, x1, y1));
for(int i = ; i < ; ++i) dis[i][x1][y1] = ;
while(step <= k) {
Node t = pre->front(); pre->pop();
if(dis[t.f][t.x][t.y] != step) continue;
if(t.x == x2 && t.y == y2) return true;
for(int i = ; i < ; ++i) {
if((t.f + ) % == i) continue;
int x = t.x + fx[i], y = t.y + fy[i], d = dis[t.f][t.x][t.y] + (t.f != i);
if(mat[x][y] == '.' && d < dis[i][x][y]) {
dis[i][x][y] = d;
if(t.f == i) pre->push(Node(i, x, y));
else cur->push(Node(i, x, y));
}
}
if(pre->empty()) {
step++;
if(cur->empty()) break;
swap(pre, cur);
}
}
return false;
} int main() {
scanf("%d", &T);
while(T--) {
scanf("%d%d", &n, &m);
memset(mat, , sizeof(mat));
for(int i = ; i <= n; ++i) scanf("%s", &mat[i][]);
scanf("%d%d%d%d%d", &k, &y1, &x1, &y2, &x2);
puts(solve() ? "yes" : "no");
}
}