zoukankan      html  css  js  c++  java
  • poj3626

    bfs

    View Code
    #include <iostream>
    #include
    <cstdio>
    #include
    <cstdlib>
    #include
    <cstring>
    using namespace std;

    #define maxx 1005
    #define inc 502
    #define maxn maxx * maxx

    struct Point
    {
    int x, y;
    } q[maxx
    * maxx];

    int n, cx, cy;
    bool vis[maxx][maxx];
    bool map[maxx][maxx];
    int dist[maxx][maxx];
    int dir[4][2] =
    {
    {
    0, 1 },
    {
    1, 0 },
    {
    0, -1 },
    {
    -1, 0 } };

    bool ok(Point &a)
    {
    if (a.x < 0 || a.y < 0 || a.x >= maxx || a.y >= maxx)
    return false;
    return !vis[a.x][a.y] && !map[a.x][a.y];
    }

    int bfs()
    {
    int front = 0;
    int rear = 1;
    q[
    0].x = inc;
    q[
    0].y = inc;
    memset(vis,
    0, sizeof(vis));
    vis[inc][inc]
    = true;
    dist[inc][inc]
    = 0;
    while (front != rear)
    {
    Point a
    = q[front++];
    if (front == maxn)
    front
    = 0;
    for (int i = 0; i < 4; i++)
    {
    Point b;
    b.x
    = a.x + dir[i][0];
    b.y
    = a.y + dir[i][1];
    if (ok(b))
    {
    q[rear
    ++] = b;
    if (rear == maxn)
    rear
    = 0;
    dist[b.x][b.y]
    = dist[a.x][a.y] + 1;
    vis[b.x][b.y]
    = true;
    if (b.x == cx && b.y == cy)
    return dist[b.x][b.y];
    }
    }
    }
    return -1;
    }

    int main()
    {
    //freopen("t.txt", "r", stdin);
    scanf("%d%d%d", &cx, &cy, &n);
    cx
    += inc;
    cy
    += inc;
    memset(map,
    0, sizeof(map));
    for (int i = 0; i < n; i++)
    {
    int a, b;
    scanf(
    "%d%d", &a, &b);
    a
    += inc;
    b
    += inc;
    map[a][b]
    = true;
    }
    int ans = bfs();
    printf(
    "%d\n", ans);
    return 0;
    }
  • 相关阅读:
    java将一个或者多个空格进行分割
    Oracle decode()函数
    javascript 匿名函数和模块化
    javascript Math函数
    javascript 数组Array排序
    jQuery 获取屏幕高度、宽度
    fastJson 转换日期格式
    QNX Development Tools Based on Eclipse IDE
    Eclipse equinox implementation of OSGi
    Eclipse SWT
  • 原文地址:https://www.cnblogs.com/rainydays/p/2105053.html
Copyright © 2011-2022 走看看