近期东六宿舍楼小偷很聪明,他们总是能寻找到偷窃后逃跑的路线,为了抓到他们,我们需要知道他们逃跑的路线,请你帮忙找出他们逃跑的路线(为简单化问题,我们保证最多只有一条逃跑路径,且起点为( 0 , 0 ),终点( 4 , 4)为,不能斜线逃跑,若终点有人拦截,也为逃跑失败)。
输入
一个5*5矩阵,用空格隔开 0表示可行走路径,1表示障碍,逃跑起点为左上,终点为右下
输出
逃跑线路,见输出示例(请注意x,y轴方向)如果没有路可以逃,则输出: "No Way!"(不含冒号和引号)
样例输入
0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 0 0 0 0
样例输出
(0,0) (0,1) (0,2) (0,3) (0,4) (1,4) (2,4) (3,4) (4,4)
#include <vector> #include <iostream> using namespace std; const int maze_size=5; int maze[maze_size+2][maze_size+2]; int state[maze_size+2][maze_size+2]; bool get; int num=2; struct node{ int x;int y;node *last; }; vector<node> outlet; node finish; node start; void maze_creat(){ int i,j; for(i=0;i<=maze_size+1;i++) for(j=0;j<=maze_size+1;j++) if((i==0)||(i==maze_size+1)||(j==0)||(j==maze_size+1)) { maze[i][j]=1;state[i][j]=0; } for(i=1;i<=maze_size;++i) for(j=1;j<=maze_size;++j){ cin>>maze[j][i];state[j][i]=0;} start.x=1; start.y=1; finish.x=5; finish.y=5; get=false; return; } void seek(node now){ if(now.x==finish.x&&now.y==finish.y){ get=true; outlet.push_back(now);return; } node next; state[now.x][now.y]=1; if(maze[now.x][now.y+1]==0&&state[now.x][now.y+1]==0&&get==false){ next.x=now.x;next.y=now.y+1;next.last=&now;seek(next);} if(maze[now.x][now.y-1]==0&&state[now.x][now.y-1]==0&&get==false){ next.x=now.x;next.y=now.y-1;next.last=&now;seek(next);} if(maze[now.x+1][now.y]==0&&state[now.x+1][now.y]==0&&get==false){ next.x=now.x+1;next.y=now.y;next.last=&now;seek(next);} if(maze[now.x-1][now.y]==0&&state[now.x-1][now.y]==0&&get==false){ next.x=now.x-1;next.y=now.y;next.last=&now;seek(next);} if(get==true)outlet.push_back(now); return; } void display(){ vector<node>::size_type end_entry=outlet.size()-1; while(!outlet.empty()){ cout<<"("<<outlet[end_entry].x-1<<","<<outlet[end_entry].y-1<<")"<<endl; --end_entry; outlet.pop_back(); } return; } int main() { maze_creat(); seek(start); if(get==false)cout<<"No Way!"<<endl; display(); return 0; }