• poj3083


    dfs+bfs,由于bfs的时候忘了加vis判断是否已入队,而多次超内存。

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

    #define maxn 45

    struct XPoint
    {
    int x, y, d;
    XPoint(
    int xx, int yy, int dd) :
    x(xx), y(yy), d(dd)
    {
    }
    XPoint()
    {
    }
    } s, e;

    int dir[4][2] = //r, u, l, d
    {
    {
    0, 1 },
    {
    -1, 0 },
    {
    0, -1 },
    {
    1, 0 } };
    bool map[maxn][maxn];
    bool vis[maxn][maxn];
    int n, m;
    int ansl, ansr, ans;

    bool ok(int x, int y)
    {
    if (x >= n || x < 0 || y >= m || y < 0)
    return false;
    if (!map[x][y])
    return false;
    return true;
    }

    void input()
    {
    scanf(
    "%d%d", &m, &n);
    getchar();
    for (int i = 0; i < n; i++)
    {
    for (int j = 0; j < m; j++)
    {
    char ch;
    scanf(
    "%c", &ch);
    if (ch == '.')
    map[i][j]
    = true;
    else
    map[i][j]
    = false;
    if (ch == 'S')
    {
    s.x
    = i;
    s.y
    = j;
    }
    if (ch == 'E')
    {
    e.x
    = i;
    e.y
    = j;
    map[i][j]
    = true;
    }
    }
    getchar();
    }
    if (s.x == 0)
    s.d
    = 3;
    if (s.x == n - 1)
    s.d
    = 1;
    if (s.y == 0)
    s.d
    = 0;
    if (s.y == m - 1)
    s.d
    = 2;
    }

    void dfs(XPoint a, int step, int dc)
    {
    if (a.x == e.x && a.y == e.y)
    {
    ans
    = step;
    return;
    }
    for (int i = -1; i < 3; i++)
    {
    int x, y, d;
    d
    = (a.d + i * dc + 4) % 4;
    x
    = a.x + dir[d][0];
    y
    = a.y + dir[d][1];
    if (ok(x, y))
    {
    dfs(XPoint(x, y, d), step
    + 1, dc);
    break;
    }
    }
    }

    void bfs()
    {
    int x, y;
    memset(vis,
    0, sizeof(vis));
    queue
    <XPoint> q;
    s.d
    = 1;
    q.push(s);
    while (!q.empty())
    {
    XPoint temp
    = q.front();
    q.pop();
    for (int i = 0; i < 4; i++)
    {
    x
    = temp.x + dir[i][0];
    y
    = temp.y + dir[i][1];
    if (e.x == x && e.y == y)
    {
    ans
    = temp.d + 1;
    return;
    }
    if (ok(x, y) && !vis[x][y])
    {
    q.push(XPoint(x, y, temp.d
    + 1));
    vis[x][y]
    = true;
    }
    }
    }
    }

    int main()
    {
    //freopen("D:\\t.txt", "r", stdin);
    int t;
    scanf(
    "%d", &t);
    while (t--)
    {
    input();
    dfs(s,
    1, -1);
    ansl
    = ans;
    dfs(s,
    1, 1);
    ansr
    = ans;
    bfs();
    printf(
    "%d %d %d\n", ansl, ansr, ans);
    }
    return 0;
    }
  • 相关阅读:
    洛谷-P1591 阶乘数码
    洛谷-P1328 生活大爆炸版石头剪刀布
    git的使用
    docker下载命令
    springboot学习笔记
    内部类被实例化才会被加载进内存测试
    springboot环境搭建遇到的问题
    Java多线程的锁机制
    spring JdbcTemplate学习
    多线程循环注意
  • 原文地址:https://www.cnblogs.com/rainydays/p/1976875.html
Copyright © 2020-2023  润新知