洛谷题单指南-进阶搜索-P2960 [USACO09OCT] Invasion of the Milkweed G

原题链接:https://www.luogu.com.cn/problem/P2960

题意解读:就是一道floodfill问题,注意输入中y表示行,x表示列,代码中可以反过来。题意就是在x*y的方格矩阵中,.表示空地,*表示障碍,从(mx,my)开始进行洪水填充,求经过几步可以填满所有空地。

解题思路:直接使用BFS洪水填充算法即可,记录每一次扩充节点的深度,并更新最大深度即为答案。

100分代码:

#include <bits/stdc++.h>
using namespace std;

const int N = 105;
int x, y, mx, my; 
char p[N][N];
bool vis[N][N];
int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};

struct Node
{
    int x, y, dist;
};

int bfs(int sx, int sy)
{
    int res = 0;
    queue<Node> q;
    q.push({sx, sy, 0});
    vis[sx][sy] = true;

    while(q.size())
    {
        Node node = q.front(); q.pop();
        for(int i = 0; i < 8; i++)
        {
            int nx = node.x + dx[i];
            int ny = node.y + dy[i];
            if(nx < 1 || nx > x || ny < 1 || ny > y) continue;
            if(vis[nx][ny] || p[nx][ny] == '*') continue;
            vis[nx][ny] = true;
            q.push({nx, ny, node.dist + 1});
            res = max(res, node.dist + 1);
        }
    }

    return res;
}

int main()
{
    cin >> y >> x >> my >> mx; //输入时y表示列,x表示行
    for(int i = x; i >= 1; i--)
    {
        for(int j = 1; j <= y; j++)
        {
            cin >> p[i][j];
        }
    }
    cout << bfs(mx, my);
    return 0;
}

 

posted @ 2025-02-25 10:18  hackerchef  阅读(68)  评论(0)    收藏  举报