zoukankan      html  css  js  c++  java
  • hdu 2822 bfs

    问题可以抽象为求起点到终点的最短路,其中经过x的代价是0,而经过.的代价是1,bfs的时候用优先队列即可。

     1 #include <iostream>
     2 #include <cstring>
     3 #include <cstdio>
     4 #include <queue>
     5 using namespace std;
     6 
     7 const int N = 1001;
     8 char maze[N][N];
     9 bool visit[N][N];
    10 int dx[] = { 0, 0, 1, -1 };
    11 int dy[] = { 1, -1, 0, 0 };
    12 int n, m, sx, sy, ex, ey;
    13 
    14 bool ok( int x, int y )
    15 {
    16     return x >= 0 && x < n && y >= 0 && y < m && !visit[x][y];
    17 }
    18 
    19 struct Node 
    20 {
    21     int x, y, t;
    22     Node(){}
    23     Node( int _x, int _y, int _t )
    24     {
    25         x = _x, y = _y, t = _t;
    26     }
    27     bool operator < ( const Node & o ) const 
    28     {
    29         return t > o.t;
    30     }
    31 };
    32 
    33 priority_queue<Node> q;
    34 
    35 int bfs()
    36 {
    37     while ( !q.empty() ) q.pop();
    38     memset( visit, 0, sizeof(visit) );
    39     q.push( Node( sx, sy, 0 ) );
    40     visit[sx][sy] = 1;
    41     while ( !q.empty() ) 
    42     {
    43         Node cur = q.top();
    44         q.pop();
    45         if ( cur.x == ex && cur.y == ey ) return cur.t;
    46         for ( int i = 0; i < 4; i++ )
    47         {
    48             int x = cur.x + dx[i];
    49             int y = cur.y + dy[i];
    50             if ( ok( x, y ) )
    51             {
    52                 int d = maze[x][y] == '.' ? 1 : 0;
    53                 q.push( Node( x, y, cur.t + d ) );
    54                 visit[x][y] = 1;
    55             }
    56         }
    57     }
    58     return -1;
    59 }
    60 
    61 int main ()
    62 {
    63     while ( scanf("%d%d", &n, &m) != EOF )
    64     {
    65         if ( !n && !m ) break;
    66         for ( int i = 0; i < n; i++ )
    67         {
    68             scanf("%s", maze[i]);
    69         }
    70         scanf("%d%d%d%d", &sx, &sy, &ex, &ey);
    71         sx--, sy--, ex--, ey--;
    72         int ans = bfs();
    73         printf("%d
    ", ans);
    74     }
    75     return 0;
    76 }
  • 相关阅读:
    ExtJs 第二章,Ext.form.Basic表单操作
    linux centos 下php的mcrypt扩展
    curl_errno错误码说明
    centos 安装composer
    虚拟机centOs Linux与Windows之间的文件传输
    CentOS 6.4 linux下编译安装 LNMP环境
    CentOS 6.4 php-fpm 添加service 添加平滑启动/重启
    CentOS 6.4 linux下编译安装MySQL5.6.14
    centOS linux 下PHP编译安装详解
    centOS linux 下nginx编译安装详解
  • 原文地址:https://www.cnblogs.com/huoxiayu/p/4856748.html
Copyright © 2011-2022 走看看