ACM篇:POJ 1383--Labyrinth

本文介绍了一种寻找迷宫中最长路径的算法实现。通过两次宽度优先搜索(BFS),找到从任意点出发可达的最远距离。文章提供了完整的C++代码示例,并解释了如何避免超时错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

随机找一点宽搜,再从最远点宽搜一次,取最大路径。

随机找点时明明两个循环,我却只写了一个break,结果多次
超时。
看来还是函数的return比较方便。

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <vector>
#include <cstdlib>

#define min(a,b) (((a) < (b)) ? (a) : (b))
#define max(a,b) (((a) > (b)) ? (a) : (b))
using namespace std;
const int MAX = 1000;
int n;
int m;

struct Point
{
    int r;
    int c;
    int step;
    Point(int r=0, int c=0, int step=0)
    {
        this->r = r;
        this->c = c;
        this->step = step;
    }
};
int readchar()
{
    int t;
    while (t = getchar())
    {
        if (t == '#' || t == '.')
            return t;
    }
}
void mymemset(bool visit[][MAX+2])
{
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            visit[i][j] = false;
}
bool in_maze(int r, int c)
{
    return (r >= 1 && r <= n && c >= 1 && c <= m);
}
char maze[MAX+2][MAX+2];
void read_maze()
{
    for (int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++)
            maze[i][j] = readchar();
}

const int ROW[] = {0 ,0, 1, -1};
const int COL[] = {1, -1, 0, 0};
bool visit[MAX+2][MAX+2];
queue<Point> q;
Point ans;

Point _find()
{
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
        {
            if (maze[i][j] == '.')
                return Point(i, j, 0);
        }
    return Point(0, 0, 0);
}
int _explore(int r, int c)
{
    memset(visit, 0, sizeof(visit));
    while (!q.empty())
        q.pop();

    q.push(Point{r, c, 0});
    visit[r][c] = true;
    while (!q.empty())
    {
        Point head = q.front();
        q.pop();

        if (head.step > ans.step)
            ans = head;

        for (int i = 0; i < 4; i++)
        {
            int nr = head.r + ROW[i];
            int nc = head.c + COL[i];
            if (!visit[nr][nc] && maze[nr][nc] == '.'&& in_maze(nr, nc))
            {
                q.push(Point{nr, nc, head.step+1});
                visit[nr][nc] = true;
            }
        }   
    }
}

int main()
{
    int T;
    int kase = 0;
    scanf("%d", &T);
    while (++kase <= T)
    {
        scanf("%d%d", &m, &n);
        read_maze();

        ans = _find();

        _explore(ans.r, ans.c);
        _explore(ans.r, ans.c);

        printf("Maximum rope length is %d.\n", ans.step);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值