POJ-3984,迷宫问题(BFS)

简介: POJ-3984,迷宫问题(BFS)

Description:


定义一个二维数组

int maze[5][5] = {

0, 1, 0, 0, 0,


0, 1, 0, 1, 0,


0, 0, 0, 0, 0,


0, 1, 1, 1, 0,


0, 0, 0, 1, 0,


};


它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。  


Input:


一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。


Output:


左上角到右下角的最短路径,格式如样例所示。


Sample Input:


0 1 0 0 0


0 1 0 1 0


0 0 0 0 0


0 1 1 1 0


0 0 0 1 0


Sample Output:


(0, 0)


(1, 0)


(2, 0)


(2, 1)


(2, 2)


(2, 3)


(2, 4)


(3, 4)


(4, 4)  


程序代码:


#include<stdio.h>
#include<string.h>
struct node
{
  int x,y,pre;
}q[50];
int head=0,tail=0;
int a[5][5],vis[5][5];
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
void bfs(int x1,int y1,int x2,int y2)
{
  q[0].x=x1;
  q[0].y=y1;
  q[0].pre=-1;
  tail++;//队尾向后移动 
  vis[x1][y1]=1;//标记 
  while(head<tail)
  {
    for(int i=0;i<4;i++)
    {
      int tx=q[head].x+dir[i][0];
      int ty=q[head].y+dir[i][1];
      if(tx<0||tx>=5||ty<0||ty>=5||vis[tx][ty]==1||a[tx][ty]==1)
        continue;//出界,或者这个点已经走过,或者这个点是障碍 
      q[tail].x=tx;
      q[tail].y=ty;
      q[tail].pre=head;
      tail++;
      vis[tx][ty]=1;
      if(tx==x2&&ty==y2)//走到迷宫出口 
        return ;
    }
    head++;
  }
}
void print(node now)
{
  if(now.pre==-1)
    printf("(%d, %d)\n",now.x,now.y);
  else
  {
    print(q[now.pre]);
    printf("(%d, %d)\n",now.x,now.y);
  } 
}
int main()
{
  for(int i=0;i<5;i++)
    for(int j=0;j<5;j++)
      scanf("%d",&a[i][j]);
  bfs(0,0,4,4);//带入起点和终点坐标 
  print(q[tail-1]);//将队列中的元素依次输出 
  return 0; 
}


相关文章
|
3月前
|
存储 算法
使用 BFS 解决走迷宫问题
使用 BFS 解决走迷宫问题
37 1
|
3月前
|
算法 Java C++
走迷宫(BFS)
走迷宫(BFS)
27 0
|
9月前
|
Java
BFS广度优先遍历——Acwing 844. 走迷宫
BFS广度优先遍历——Acwing 844. 走迷宫
53 0
|
存储 定位技术 C++
【31. 走迷宫(BFS)】
## 思路 - 用 `g[n][m] `存储地图,`d[n][m]` 存储起点到 n,m 的距离。 - 从起点开始广度优先遍历地图。 - 当地图遍历完,就求出了起点到各个点的距离,输出`d[n][m]`即可。
235 0
【31. 走迷宫(BFS)】
HDU-1874,畅通工程续(Floyd最短路)
HDU-1874,畅通工程续(Floyd最短路)
|
人机交互
POJ-2524,Ubiquitous Religions(并查集模板题)
POJ-2524,Ubiquitous Religions(并查集模板题)
|
并行计算 算法 Java
HDU 1874 畅通工程续【Floyd算法实现】
畅通工程续 Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 53806    Accepted Submission(s): 20092 Problem Description 某省自从实行了很多年的畅通工程计划后,终于修建了很多路。
1063 0

热门文章

最新文章