// Created by baicai on 14-5-10.
// 递归问题
/* 递归中两个重要的点 : 1.递归公式 2.终止条件 */
/* 函数的局部变量存在栈中,可能会栈溢出,所以可以考虑使用全局数组,或者动态分配数组 */
/* 游戏问题: 类似迷宫求解,自相似性表现在每走一步的探测方式相同,可以用递归方法求解,
通过枚举出所有从起点到终点的路径
*/
// 需要一个记录
// 方向数组 to[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
/*
for(int i=0;i<4;i++)
int x = now_x + to[i][0];
int y = now_y + to[i][1];
f = i; // 方向
限制:
边界
(x > -1) && x<( w+2) && (y>-1) && (y< h+2)
有没有游戏卡片曾走过
((board[y][x] == ' ') && ( mark[y][x] == false ))
已经到达终点
(x == end_x) && (y == end_y) && (borad[y][x] == 'X')
终止条件: T1&&(T2||T3)
*/
#include <stdio.h>
#include <memory.h>
#include <iostream>
using namespace std;
int W;
int H;
int board[77][77];
int to[4][2] = {{0,1},{1,0},{0,-1},{-1,0}}; // 东南西北
bool mark[77][77]; // 标记是否走过
int minstep;
int count;
void Search(int x,int y,int x_end,int y_end,int f,int step){
/* 终止条件 */
if (step > minstep) {
return;
}
if (x == x_end && y == y_end) {
if (step < minstep) {
minstep = step;
return;
}
}
// 枚举搜寻方向
for (int i = 0; i < 4; i++) {
int _x = x + to[i][0];
int _y = y + to[i][1];
// 在下列几种情况下 继续递归 在板内的情况的 1. 找到 2. 没有走过 3.
if ((((_x > -1) && _x < (W+2) && (_y>-1)&&(_y<H+2)) && (((_x == x_end)&&(_y == y_end) && board[_y][_x]=='X' ) || (((mark[_y][_x] ==false && (board[_y][_x] == ' '))))))) {
mark[_y][_x] = true;
if (f == i) {
Search(_x, _y, x_end, y_end, i, step);
}
else{
Search(_x, _y, x_end, y_end, i, step+1);
}
mark[_y][_x] = false;
}
}
}
int main(){
int Boardnum = 0;
while (cin>>W>>H) {
if (W==0 && H == 0) {
break;
}
++Boardnum;
printf("Board #%d:\n",Boardnum);
int i,j;
for (i = 0; i < (W+2); i++) {
board[0][i] = board[i][0] = ' ';
}
for (i = 1 ; i<=H; i++) {
getchar(); // 丢弃回车
for (j=1; j<=W; j++) {
board[i][j] = getchar();
}
}
for (i=0; i<=W; i++) {
board[H+1][i+1] = ' ';
board[i+1][W+1] = ' ';
}
int begin_x,begin_y,end_x,end_y,count = 0;
while (cin>>begin_x>>begin_y>>end_x>>end_y) // 少了一些条件语句
{
count++;
memset(mark, false, sizeof(mark));
minstep = 9999999;
Search(begin_x, begin_x, end_x, end_y, -1, 0);
if (minstep < 9999999) {
cout<<"Pari"<<count<<" "<<"segment:"<<minstep<<endl;
}
else
cout<<"impossibe"<<count<<endl;
}
cout<<endl;
}
return 0;
}