• 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)

    思路:

    1.BFS,需要注意的就是打印的是路径点。所以需要储存路径最后再输出。储存路径:在走每一个节点时记录它的父节点的编号。

    2.当然因为这个题就一组数据可以肉眼观测打表做...

    坑点:输出格式(a, b)b左边有个空格...


     1 #include<cstdio>
     2 #include<queue>
     3 using namespace std;
     4 int map[5][5];
     5 int dir[4][2]={{1,0},{0,-1},{-1,0},{0,1}};
     6 
     7 struct node{
     8     int x,y,pre,n;//n为编号,pre为父节点的编号
     9 }p[100];
    10 
    11 void print(int i){
    12     if(p[i].pre!=-1) {
    13         print(p[i].pre);
    14         printf("(%d, %d)
    ",p[i].x,p[i].y);
    15     }
    16     else{
    17         printf("(%d, %d)
    ",p[i].x,p[i].y);
    18     }
    19 }
    20 
    21 void bfs(){
    22     int cnt=0;
    23     p[cnt].x=0,p[cnt].y=0,p[cnt].pre=-1;
    24     map[0][0]=1;
    25     queue<node>q;
    26     node head,next;
    27     head.x=0,head.y=0,head.n=0;
    28     q.push(head);
    29     while(!q.empty()){
    30 
    31         head=q.front();
    32         q.pop();
    33 
    34         if(head.x==4&&head.y==4){
    35             print(cnt);
    36             return;
    37         }
    38         
    39         for(int i=0;i<4;i++){
    40             next.x=head.x+dir[i][0];
    41             next.y=head.y+dir[i][1];
    42             
    43             if(next.x<0||next.x>4||next.y<0||next.y>4||map[next.x][next.y]) continue;
    44             
    45             map[next.x][next.y]=1;            
    46             cnt++;
    47             next.n=cnt;
    48             p[cnt].x=next.x,p[cnt].y=next.y;
    49             p[cnt].pre=head.n;        
    50             q.push(next);
    51         }
    52     }
    53 }
    54 
    55 int main(){
    56     for(int i=0;i<5;i++)
    57     for(int j=0;j<5;j++)
    58         scanf("%d",&map[i][j]);
    59     bfs();    
    60     return 0;
    61 } 

     打表:

    1 #include<cstdio>
    2 using namespace std;
    3 int main(){
    4     printf("(0, 0)
    (1, 0)
    (2, 0)
    (2, 1)
    (2, 2)
    (2, 3)
    (2, 4)
    (3, 4)
    (4, 4)
    ");
    5     return 0;
    6 } 
  • 相关阅读:
    [spoj DISUBSTR]后缀数组统计不同子串个数
    [poj 3261]后缀数组+滑窗最小值
    [poj 1743]差分+后缀数组
    [codechef MEXDIV]Mex division
    JavaScript中的数组和对象 增删遍
    ajax返回的值有两种方法,一种是把async:true改为false。 另一种是回调函数。
    使用smart-npm和npm安装完毕之后发现 不是内部命令和外部命令!
    移动端rem设置,自动更改html<font-size>
    总结js创建object的方式(对象)
    用css方法 可以实现多行 超出宽度 出点点点号
  • 原文地址:https://www.cnblogs.com/yzhhh/p/9974699.html
Copyright © 2020-2023  润新知