学习记录:Flood Fill(红水灌溉法)——红与黑

题目:红与黑
有一间长方形的房子,地上铺了红色、黑色两种颜色的正方形瓷砖。你站在其中一块黑色的瓷砖上,只能向相邻(上下左右四个方向)的黑色瓷砖移动。
请写一个程序,计算你总共能够到达多少块黑色的瓷砖。

输入格式
输入包括多个数据集合。
每个数据集合的第一行是两个整数 W和 H,分别表示 x方向和 y方向瓷砖的数量。在接下来的 H行中,每行包括 W个字符。每个字符表示一块瓷砖的颜色,规则如下
1)‘.’:黑色的瓷砖;
2)‘#’:红色的瓷砖;
3)‘@’:黑色的瓷砖,并且你站在这块瓷砖上。该字符在每个数据集合中唯一出现一次。

当在一行中读入的是两个零时,表示输入结束。

输出格式
对每个数据集合,分别输出一行,显示你从初始位置出发能到达的瓷砖数(记数时包括初始位置的瓷砖)。

数据范围
1≤W,H≤20

学习yls思路:找到与初始地连通的所有连通块,记录
1、BFS(使用队列,比较麻烦)
2、DFS(可能会有爆栈的风险)

BFS

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;

typedef pair<int, int> PII;
#define x first
#define y second
const int N = 25;
char g[N][N];
int m, n;

int bfs(int sx, int sy)
{
    int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
    queue<PII> q;
    q.push({sx, sy});		//将起始点入栈
    g[sx][sy] = '#';
    int res = 0;
    while(q.size())
    {
        auto t = q.front();
        q.pop();
        res ++ ;		
        for(int i = 0; i < 4; i++)
        {
            int x = t.x + dx[i], y = t.y + dy[i];
            if(x < 0 || x >= n || y < 0 || y >= m || g[x][y] != '.') continue;	//遇到边界结束,从下一个方向开始	
            g[x][y] = '#';
            q.push({x, y});
        }
    }
    return res;
}
int main()
{
    while(cin >> m >> n, m || n)	//新写法,一直接收,直到 m n都为0停止
//注意题目要求,先行后列
    {
        for(int i = 0; i < n; i ++ ) cin >> g[i];
        int x, y;
        for(int i = 0; i < n; i ++ )
            for(int j = 0; j < m; j ++ )
                if(g[i][j] == '@')		//找到起点
                {
                    x = i;
                    y = j;
                }
        cout << bfs(x, y) << endl;  //宽搜
    }
    return 0;
}

DFS

#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

const int N = 25;
int m, n;
char q[N][N];
int dx[] = {-1, 0, 1, 0};       //用坐标记录方向
int dy[] = {0, 1, 0, -1};
bool st[N][N];
int dfs(int sx, int sy)
{
    st[sx][sy] = true;
    int ans = 1;
    for(int i = 0 ; i < 4; i++)
    {
        int x = sx + dx[i] ,y = sy + dy[i];
        if(x < 0 && x > n && y < 0 && y > n) continue;
        if(st[x][y]) continue;
        if(q[x][y] != '.') continue;
        ans += dfs(x, y);
    }
    return ans;
}
int main()
{
    while(cin >> m >> n, m || n)
    {
        int x, y;
        for(int i = 0; i < n; i ++ ) cin >> q[i];
        for(int i = 0; i < n; i ++ )
            for(int j = 0; j < m; j ++ )
                if(q[i][j] == '@')
                {
                     x = i; 
                     y = j;
                }
        memset(st, 0, sizeof st);  //一次结束后清空
        cout << dfs(x, y) << endl;   
    }    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值