zoukankan      html  css  js  c++  java
  • poj 3984 迷宫问题(bfs)

    迷宫问题
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 11663   Accepted: 6978

    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)

    Source

     

     

    并不是第一次遇到搜索题,这道题可以作为一道模板式广搜,不过这是我第一次接触需要输出搜索的全部路径的题,思路并不是很清晰,借助了别人的代码,完成了代码的编写。

    题意:中文题,很好理解。

    附上代码:

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <queue>
     4 using namespace std;
     5 int map[10][10];   //记录迷宫的路径
     6 int f[4][2]= {0,1,0,-1,1,0,-1,0};   //搜索的方向
     7 struct node
     8 {
     9     int x,y,t;  //采用结构体存储,x,y为当前的坐标,t为当前所用的步数
    10     short l[30];  //记录每一次转弯的方向
    11 } s1,s2;
    12 void BFS()
    13 {
    14     queue<node> q;
    15     while(!q.empty())   //清空队列
    16         q.pop();
    17     s1.x=0;
    18     s1.y=0;
    19     s1.t=0;
    20     map[0][0]=1;     //标记起点,走过的点全部标记为1
    21     q.push(s1);
    22     while(!q.empty())
    23     {
    24         s1=q.front();
    25         q.pop();
    26         if(s1.x==4&&s1.y==4)
    27         {
    28             int a=0,b=0;
    29             for(int i=0; i<=s1.t; i++)
    30             {
    31                 printf("(%d, %d)
    ",a,b);
    32                 a+=f[s1.l[i]][0];     // 只有正确的路才能走到最后的终点
    33                 b+=f[s1.l[i]][1];
    34             }
    35 
    36         }
    37         for(int i=0; i<4; i++)
    38         {
    39             s2=s1;
    40             s2.x=s1.x+f[i][0];
    41             s2.y=s1.y+f[i][1];
    42             if(s2.x>=0&&s2.x<5&&s2.y>=0&&s2.y<5&&!map[s2.x][s2.y])
    43             {
    44                 map[s2.x][s2.y]=1;
    45                 s2.t=s1.t+1;
    46                 s2.l[s1.t]=i;     //记录每一次转弯的方向
    47                 q.push(s2);
    48             }
    49         }
    50     }
    51 }
    52 int main()
    53 {
    54     int i,j;
    55     for(i=0; i<5; i++)
    56         for(j=0; j<5; j++)
    57             scanf("%d",&map[i][j]);
    58     BFS();
    59     return 0;
    60 }
  • 相关阅读:
    高级特性(4)- 数据库编程
    UVA Jin Ge Jin Qu hao 12563
    UVA 116 Unidirectional TSP
    HDU 2224 The shortest path
    poj 2677 Tour
    【算法学习】双调欧几里得旅行商问题(动态规划)
    南洋理工大学 ACM 在线评测系统 矩形嵌套
    UVA The Tower of Babylon
    uva A Spy in the Metro(洛谷 P2583 地铁间谍)
    洛谷 P1095 守望者的逃离
  • 原文地址:https://www.cnblogs.com/pshw/p/4754664.html
Copyright © 2011-2022 走看看