#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
typedef struct
{
int r;
int c;
int step;
}LOC;//點的屬性
typedef struct
{
int sr, sc, er, ec;
}POR;//傳送門的屬性
char buf[1000];
char map[101][101];//地圖
int N, M, W;
queue<LOC> Q;//點的隊列
vector<POR> P;//存儲所有的傳送門信息
int sr, sc, er, ec;//start, end, row, col
int dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};//代表四個方向
void addLOC(int r, int c, int step)
{
LOC tmp;
tmp.c = c;
tmp.r = r;
tmp.step = step;
Q.push(tmp);
map[r][c] = '2';
}//在隊列中添加一個點,并在地圖上留下標記‘2’,防止重復(0表示可以走,1表示墻,2表示走過)
void solve()
{
int i;
addLOC(sr, sc, 0);//添加第一個點(起點)
here:
while(!Q.empty())
{
LOC cur = Q.front();//提取這個點的信息
Q.pop();//處理后便可以退出隊列
if(cur.c == ec && cur.r == er)
{
cout << cur.step << endl;
return;
}//如果到達終點,就輸出當前的步數
for(i = 0; i < W; ++i)
{
if(P[i].sr == cur.r && P[i].sc == cur.c)
{
if(map[P[i].er][P[i].ec] == '0')
addLOC(P[i].er, P[i].ec, cur.step+1);
goto here;
}
}//遍歷傳送門,如果踩到了,而且傳送到的地方不是墻也沒有走過,就添加這個點,繼續看隊列中的下一個點
//否則此路不通,看隊列中的下一個點
int tmpr, tmpc, i;
for(i = 0; i < 4; ++i)
{
tmpr = cur.r+dir[i][0];
tmpc = cur.c+dir[i][1];
if(tmpr>=0 && tmpr<N && tmpc>=0 && tmpc<M && map[tmpr][tmpc]=='0')
{
addLOC(tmpr, tmpc, cur.step+1);
}
}//嘗試四個方向,如果某個方向有路(不是墻也沒有到地圖外也沒有走過),就添加這個點
}
cout << "die" << endl;//如果一直都沒有return,輸出die
}
//廣度優先搜索,使用隊列實現
int main()
{
//freopen("data.txt", "r", stdin);
int num, i;
cin >> num;
while(num--)
{
P.clear();//把上一個case的陷阱信息置空
while(!Q.empty())
Q.pop();//把上一個case的點的隊列置空置空
cin >> N >> M;//輸入行和列數
gets(buf);//吃掉回車
for(i = 0; i < N; ++i)
gets(map[i]);//讀入地圖
cin >> W;//傳送門個數
for(i = 0; i < W; ++i)
{
POR tmp;
cin >> tmp.sr >> tmp.sc >> tmp.er >> tmp.ec;
P.push_back(tmp);
}//讀入傳送門并把它加入數組
cin >> sr >> sc >> er >> ec;//輸入起點和終點的行,列
solve();//調用函數解決迷宮
}
return 0;
}
solve()函數采用深度優先搜索算法,遍歷離當前點最近的點(或傳送門到達的點)加入隊列,被加入的點在與“推出它的點”同步數的點被處理完之前都不會被處理,換句話說,處理一個點過后可能會在隊尾加入數個點(也可能不加入),加入后需要做的是繼續提取隊頭的點進行操作。廣度優先可以想象為河流的分流過程。