zoukankan      html  css  js  c++  java
  • POJ 3984 迷宫问题

    第二道广搜的问题

    虽然思路很清晰,可真要自己把代码敲出来并不是一件容易的事

    用一维数组模拟一个队列,head和tail分别记录队首和队尾

    先将迷宫的起点入队,然后向四个方向拓展,如果没有出界或者没有遇到墙壁,那么入队,然后队首出队

    知道搜到迷宫的出口为止

     1 //#define LOCAL
     2 #include <iostream>
     3 #include <cstdio>
     4 #include <cstring>
     5 using namespace std;
     6 
     7 struct Point
     8 {
     9     int x, y, pre;
    10 }queue[30];
    11 
    12 int map[7][7];
    13 int head = 0, tail = 1;
    14 int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    15 
    16 void output(int i)
    17 {
    18     if(queue[i].pre != -1)
    19     {
    20         output(queue[i].pre);
    21         printf("(%d, %d)
    ", queue[i].x, queue[i].y);
    22     }
    23 }
    24 
    25 int main(void)
    26 {
    27     #ifdef LOCAL
    28         freopen("3984in.txt", "r", stdin);
    29     #endif
    30 
    31     for(int i = 0; i < 5; ++i)
    32         for(int j = 0; j < 5; ++j)
    33             scanf("%d", &map[i][j]);
    34     //将迷宫的起点入队
    35     queue[0].x = queue[0].y = 0;
    36     queue[0].pre = -1;
    37     map[0][0] = 1;
    38     printf("(0, 0)
    ");
    39     while(head < tail)
    40     {
    41         for(int i = 0; i < 4; ++i)
    42         {
    43             int xx = queue[head].x + dir[i][0];
    44             int yy = queue[head].y + dir[i][1];
    45             if(xx<0 || xx >=5 || yy<0 || yy>=5 || map[xx][yy])
    46                 continue;
    47             map[xx][yy] = 1;    //标记已经走过
    48             queue[tail].x = xx;
    49             queue[tail].y = yy;
    50             queue[tail++].pre = head;
    51             if(xx == 4 && yy == 4)
    52                 output(head);//找到要搜索的目标,开始输出
    53         }
    54         ++head;//队首元素出队
    55     }
    56     printf("(4, 4)
    ");
    57     return 0;
    58 }
    代码君
  • 相关阅读:
    D. Renting Bikes 二分
    Maximum Absurdity DP + 数学
    模拟 H
    Secrets 数论
    A. Knight Tournament SET的应用
    B. Xenia and Hamming Codeforces 256B GCD,LCM处理字符串
    Alternate Task UVA11728 暴力枚举
    GCD Extreme (II) 欧拉函数的应用
    Bit Magic HDU 4421 2-Sat
    Encoding http://acm.hdu.edu.cn/showproblem.php?pid=1020
  • 原文地址:https://www.cnblogs.com/AOQNRMGYXLMV/p/3904075.html
Copyright © 2011-2022 走看看