第二周作业 A题

A题 迷宫

题目描述:

东东有一张地图,想通过地图找到妹纸。地图显示,0表示可以走,1表示不可以走,左上角是入口,右下角是妹纸,这两个位置保证为0。既然已经知道了地图,那么东东找到妹纸就不难了,请你编一个程序,写出东东找到妹纸的最短路线。

Input

输入是一个5 × 5的二维数组,仅由0、1两数字组成,表示法阵地图。

Output

输出若干行,表示从左上角到右下角的最短路径依次经过的坐标,格式如样例所示。数据保证有唯一解。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 1 0 1 0
0 0 0 1 0
0 1 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(3, 0)
(3, 1)
(3, 2)
(2, 2)
(1, 2)
(0, 2)
(0, 3)
(0, 4)
(1, 4)
(2, 4)
(3, 4)
(4, 4)

解题思路:迷宫问题,首先想到用bfs
这个人从开始(0,0)走到(4,4)每一次无非就是上、下、左、右四个方向去不断尝试是否能走,还有就是,是否已经访问过,如果这个点可以走并且没有被访问过,则入队,我这里用到了一个数组来储存我们所经过的点,(便于以后的递归输出),最后只需要判断是否能走到x=4,y=4的点就可以了

注意事项:在输出的时候看好输出格式,逗号以后有一个空格。。。又是不看题的一天

#include<iostream>
#include<queue>
using namespace std;
struct point{
 int x;
 int y;
 point(){}
 point(int xx,int yy)
 {
  this->x=xx;
  this->y=yy;
 }
}; 
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
int a[5][5];
int vis[5][5];
point **path;
bool bfs()
{
 queue<point> q;
 point s(0,0);
 q.push(s);
 a[s.x][s.y]=-1;
 point now;
 while(!q.empty())
 {
  now=q.front();
  q.pop();
  for(int i=0;i<4;i++)
  {
   point next;
   next.x=now.x+dx[i];
   next.y=now.y+dy[i];
   if(next.x>=0&&next.x<5&&next.y>=0&&next.y<5&&a[next.x][next.y]==0)
   {
    q.push(next);
    a[next.x][next.y]=-1;
    path[next.x][next.y]=now;
   }
  }
 }
 if(now.x==4&&now.y==4) return true;
 else return false;
}
void output(point end)
{
 point temp=end;
 if(end.x==0&&end.y==0)
 {
  cout<<"("<<end.x<<", "<<end.y<<")"<<endl;
  return; 
 }
 else{
  temp=path[temp.x][temp.y];
  output(temp);
  if(!(temp.x==0&&temp.y==0))
  cout<<"("<<temp.x<<", "<<temp.y<<")"<<endl;
 }
 return;
}
int main()
{
 for(int i=0;i<5;i++)
  for(int j=0;j<5;j++)
  {
   vis[i][j]=0; 
   cin>>a[i][j]; 
   } 
 path=new point*[25];
 for(int i=0;i<5;i++)
  path[i]=new point[5];
 point s(0,0);
 point t(4,4);
 bfs();
 output(t);
 cout<<"(4, 4)"<<endl;
 return 0;
}
发布了20 篇原创文章 · 获赞 0 · 访问量 236

猜你喜欢

转载自blog.csdn.net/GuaXX/article/details/104975632