Day - 4 红与黑(Flood Fill算法)

考点:Flood Fill算法、bfs、dfs

洪水灌溉算法多用于网格题

bfs 写法:从所在位置开始,每次遍历该方格上下左右相邻的四个方格,如果未被开发,则将其入队并标记为已开发。

while  队列非空

{

         取出队头 t

         枚举t的4个邻格

         if  格子是陆地并且未被开发

                标记为已开发

                入队

}

#include <iostream>
#include <queue>
#include <algorithm>

using namespace std;

const int N = 25;
int w,h;
char g[N][N];

typedef pair<int,int> PII;

int bfs(int sx,int sy)
{
    queue<PII> q;
    q.push({sx,sy});
    g[sx][sy] = '#';
    int res = 0;
    
    int dx[] = {-1,0,1,0},dy[] = {0,1,0,-1};
    
    while(q.size())
    {
        auto t = q.front();
        q.pop();
        res ++ ;
        
        for(int i = 0; i < 4; i ++ )
        {
            int x = t.first + dx[i], y  = t.second + dy[i];
            if(x < 0 || x >= h || y < 0 || y >= w || g[x][y] != '.') continue;
            g[x][y] = '#';
            q.push({x,y});
        }
    }
    return res;
}
int main()
{
    while(cin >> w >> h, w || h)
    {
        for(int i = 0; i < h; i ++ ) cin >> g[i];
        
        int x,y;
        for(int i = 0; i < h; i ++ )
            for(int j = 0; j < w; j ++ )
                if(g[i][j] == '@')
                {
                    x = i;
                    y = j;
                }
            
        cout << bfs(x,y) << endl;
    }
    
    return 0;
}

 

dfs写法

dfs(x,y)

{

      将(x,y)标记为已开发;

      枚举(x,y)的4个邻格 ; //上右下左顺序

         if 邻格可走

             dfs(邻格)

}

#include <iostream>
#include <queue>
#include <algorithm>

using namespace std;

const int N = 25;

int w,h;
char g[N][N];

int dfs(int x,int y)
{
    
    int dx[] = {-1,0,1,0},dy[]={0,1,0,-1};
    g[x][y] = '#';
    int res = 1;
    
    for(int i = 0; i < 4; i ++ )
    {
        int a = x + dx[i] , b = y + dy[i];
        if(a >= 0 && a <= h && b >= 0 && b < w && g[a][b] == '.')
        res += dfs(a,b);
    }
    return res;
}

int main()
{
    while(cin >> w >> h, w || h)
    {
        for(int i = 0; i < h;i ++ ) cin >> g[i];
        
        int x,y;
        for(int i = 0; i < h; i ++ )
            for(int j = 0; j < w; j ++ )
                if(g[i][j] == '@')
                {
                    x = i;
                    y = j;
                }
        cout << dfs(x,y) << endl;
    }
    
    return 0;
}

注:int dx[] = {-1,0,1,0},dy[]={0,1,0,-1}; 可参考 → 偏移量的使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值