ACM篇:POJ 1383--Labyrinth

隨機找一點寬搜,再從最遠點寬搜一次,取最大路徑。

隨機找點時明明兩個循環,我卻只寫了一個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;
}
發佈了58 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章