电子老鼠闯迷宫
时限:1000ms 内存限制:10000K 总时限:3000ms
描述
有一只电子老鼠被困在如下图所示的迷宫中。这是一个12*12单元的正方形迷宫,黑色部分表示建筑物,白色部分是路。电子老鼠可以在路上向上、下、左、右行走,每一步走一个格子。现给定一个起点S和一个终点T,求出电子老鼠最少要几步从起点走到终点。
输入
本题包含一个测例。在测例的第一行有四个由空格分隔的整数,分别表示起点的坐标S(x.y)和终点的坐标T(x,y)。从第二行开始的12行中,每行有12个字符,描述迷宫的情况,其中'X'表示建筑物,'.'表示路.
输出
输出一个整数,即电子老鼠走出迷宫至少需要的步数。
输入样例
2 9 11 8
XXXXXXXXXXXX
X......X.XXX
X.X.XX.....X
X.X.XX.XXX.X
X.X.....X..X
X.XXXXXXXXXX
X...X.X....X
X.XXX...XXXX
X.....X....X
XXX.XXXX.X.X
XXXXXXX..XXX
XXXXXXXXXXXX
XXXXXXXXXXXX
X......X.XXX
X.X.XX.....X
X.X.XX.XXX.X
X.X.....X..X
X.XXXXXXXXXX
X...X.X....X
X.XXX...XXXX
X.....X....X
XXX.XXXX.X.X
XXXXXXX..XXX
XXXXXXXXXXXX
输出样例
28
#include <iostream> #include <queue> using namespace std; typedef struct mapnode { char data; bool visit; } mapnode; mapnode map[12][12]; typedef struct node { int posx; int posy; int countstep; } node; int main() { int startx,starty,endx,endy; cin>>starty>>startx>>endy>>endx; for(int i = 0;i < 12; i++) for(int j = 0;j < 12; j++) { cin>>map[i][j].data; map[i][j].visit = false; } /*cout<<"show"<<endl; for(int i = 0;i < 12; i++) { for(int j = 0;j < 12; j++) cout<<map[i][j].data<<" "; cout<<endl; }*/ queue<node> minequeue; node firstnode; firstnode.posx = startx-1; firstnode.posy = starty-1; firstnode.countstep = 0; map[firstnode.posy][firstnode.posx].visit = true; minequeue.push(firstnode); while(!minequeue.empty()) { node temp = minequeue.front(); minequeue.pop(); //cout<<temp.countstep<<"<"<<temp.posy+1<<","<<temp.posx+1<<">"<<endl; if(temp.posy==(endy-1)&&temp.posx==(endx-1)) { //cout<<"reach distination!!"<<endl; cout<<temp.countstep<<endl; break; } if((temp.posy+1)<12&&map[temp.posy+1][temp.posx].data=='.'&&map[temp.posy+1][temp.posx].visit==false) { node downnode; downnode.posy = temp.posy+1; downnode.posx = temp.posx; downnode.countstep = temp.countstep+1; map[temp.posy+1][temp.posx].visit = true; minequeue.push(downnode); } if((temp.posx-1)>=0&&map[temp.posy][temp.posx-1].data=='.'&&map[temp.posy][temp.posx-1].visit==false) { node leftnode; leftnode.posy = temp.posy; leftnode.posx = temp.posx-1; leftnode.countstep = temp.countstep+1; map[temp.posy][temp.posx-1].visit = true; minequeue.push(leftnode); } if((temp.posy-1)>=0&&map[temp.posy-1][temp.posx].data=='.'&&map[temp.posy-1][temp.posx].visit==false) { node upnode; upnode.posy = temp.posy-1; upnode.posx = temp.posx; upnode.countstep = temp.countstep+1; map[temp.posy-1][temp.posx].visit = true; minequeue.push(upnode); } if((temp.posx+1)<12&&map[temp.posy][temp.posx+1].data=='.'&&map[temp.posy][temp.posx+1].visit==false) { node rightnode; rightnode.posy = temp.posy; rightnode.posx = temp.posx+1; rightnode.countstep = temp.countstep+1; map[temp.posy][temp.posx+1].visit = true; minequeue.push(rightnode); } } return 0; }