/* Name:poj 1101 The Game Author: UnimenSun Date: 05/05/2011 23:15 Description: BFS */ /* 解题报告:BFS 1、只有一个注意点该题搜的不是最短路径,而是最少拐弯次数(类似于连连看),只需在BFS的同时 在满足的一个条件的情况下让它继续向下走,风见代码注释 */ #include <iostream> #include <queue> #include <cstring> using namespace std; char g[80][80]; int w, h; int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; int visited[80][80]; struct Piece { int x, y; int step; }; Piece start, goal; void bfs() { int i; memset(visited, 0, sizeof(visited)); queue<Piece> que; que.push(start); visited[start.x][start.y] = 1; while(!que.empty()) { Piece temp1 = que.front(); que.pop(); if(temp1.x==goal.x && temp1.y==goal.y && goal.step>temp1.step) { goal.step = temp1.step; } for(i=0; i<4; ++i) { Piece temp2; temp2.x = temp1.x + dir[i][0]; temp2.y = temp1.y + dir[i][1]; while(!visited[temp2.x][temp2.y] && temp2.x>=0 && temp2.x<=h+1 //在同一个方向继续向下走 && temp2.y>=0 && temp2.y<=w+1 && g[temp2.x][temp2.y]==' ') { visited[temp2.x][temp2.y] = 1; temp2.step = temp1.step+1; que.push(temp2); temp2.x += dir[i][0]; temp2.y += dir[i][1]; } } } } int main() { int i, j; int nCase = 0, nPacase; while(cin>>w>>h && w && h) { nPacase = 0; //输入并建图 for(i=1; i<=h; ++i) { cin.get(); for(j=1; j<=w; ++j) cin.get(g[i][j]); } //外围加框 for(i=0; i<=w+1; i++) { g[0][i] = ' '; g[h+1][i] = ' '; } for(i=0; i<=h+1; ++i) { g[i][0] = ' '; g[i][w+1] = ' '; } //测试图的正确性 /*for(i=0; i<=h+1; i++) { for(j=0; j<=w+1; j++) cout<<g[i][j]; cout<<endl; }*/ cout<<"Board #"<<++nCase<<":"<<endl; while(1) { cin>>start.y>>start.x>>goal.y>>goal.x; start.step = 0; goal.step = 1000000; if(start.x==0 && start.y==0 && goal.x==0 && goal.y==0) break; int bFlag = false; if(g[goal.x][goal.y] == 'X') { g[goal.x][goal.y] = ' '; bFlag = true; } bfs(); if(bFlag) g[goal.x][goal.y] = 'X'; if(goal.step == 1000000) cout<<"Pair "<<++nPacase<<": impossible."<<endl; else cout<<"Pair "<<++nPacase<<": "<<goal.step<<" segments."<<endl; } cout<<endl; } return 0; }