zoukankan      html  css  js  c++  java
  • [北大机试C]:走迷宫(BFS)

    一个迷宫由R行C列格子组成,有的格子里有障碍物,不能走;有的格子是空地,可以走。
    给定一个迷宫,求从左上角走到右下角最少需要走多少步(数据保证一定能走到)。只能在水平方向或垂直方向走,不能斜着走。
    Input第一行是两个整数,R和C,代表迷宫的长和宽。( 1<= R,C <= 40)
    接下来是R行,每行C个字符,代表整个迷宫。
    空地格子用'.'表示,有障碍物的格子用'#'表示。
    迷宫左上角和右下角都是'.'。Output输出从左上角走到右下角至少要经过多少步(即至少要经过多少个空地格子)。计算步数要包括起点和终点。Sample Input

    5 5
    ..###
    #....
    #.#.#
    #.#.#
    #.#..
    

    Sample Output

    9


    裸BFS
     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cmath>
     4 #include <cstdlib>
     5 #include <cstring>
     6 #include <string>
     7 #include <queue>
     8 using namespace std;
     9 int n,m;
    10 char a[50][50];
    11 bool vis[50][50];
    12 int dx[4] = {0,0,-1,1};
    13 int dy[4] = {1,-1,0,0};
    14 struct Node{
    15     int x,y,w;
    16 };
    17 int bfs(){
    18     queue <Node> q;
    19     Node u = Node{0,0,1};
    20     q.push(u);
    21     while(!q.empty()){
    22         Node u = q.front();
    23         q.pop();
    24         int x = u.x,y = u.y,w = u.w;
    25         for (int i = 0;i < 4;++i){
    26             int tx = x + dx[i];
    27             int ty = y + dy[i];
    28             if (tx >= 0 && tx < n && ty >= 0 && ty < m && !vis[tx][ty] && a[tx][ty] == '.'){
    29                 q.push(Node{tx,ty,w+1});
    30                 vis[tx][ty] = 1;
    31                 if (tx == n-1 && ty == m-1) return w+1;
    32             }
    33         }
    34     }
    35 }
    36 
    37 int main(){
    38     scanf("%d%d",&n,&m);
    39     for (int i = 0;i < n;++i){
    40         getchar();
    41         for (int j = 0;j <m;++j){
    42             scanf("%c",&a[i][j]);
    43         }
    44     }
    45     printf("%d
    ",bfs());
    46     return 0;
    47 }
  • 相关阅读:
    [UOJ#128][BZOJ4196][Noi2015]软件包管理器
    [UOJ#127][BZOJ4195][NOI2015]程序自动分析
    [BZOJ3653]谈笑风生
    Django 数据库查询优化
    C#中引用(ref关键字)参数
    C#中值参数的使用实例
    静态变量和实例变量
    全局变量和局部变量的理解
    C#方法定义和调用-2
    C#函数的方法定义和方法调用小议
  • 原文地址:https://www.cnblogs.com/mizersy/p/12232153.html
Copyright © 2011-2022 走看看