Oil Deposits POJ - 1562 (DFS)

https://vjudge.net/problem/POJ-1562

一道基础的DFS问题,其中牵扯到了染色的问题。与一般的城堡寻屋子问题不一样的时,屋子之间不是相邻的(存在*)。所以需要先写一个枚举,找到一个屋子就Dfs与之相邻的所有@。

注意初始化和边界问题。

//Oil Deposits
#include<cstdio>
#include<cstring>
using namespace std;

const int maxn = 110;
char grid[maxn][maxn];
int color[maxn][maxn], colorNum = 0; //染色,0表示未染色,-1表示不为油,1-n表示颜色
int m, n;
int action[][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {-1, -1}, {+1, -1}, {-1,+1}};
void Dfs(int x, int y)
{
    color[x][y] = colorNum; //染色

    //对于每个可移向的方向
    for(int i = 0; i < 8; i++){
        int sx = x+action[i][0], sy = y+action[i][1];
        if(sx>0 && sx<=m && sy>0 && sy<=n && grid[sx][sy]=='@' && color[sx][sy]==0 && (sx!=x || sy!=y))
            Dfs(sx, sy);
    }
}
int main()
{
    while(scanf("%d%d",&m,&n)!=EOF && m!=0){
        memset(grid, '*', sizeof(grid)), memset(color, 0, sizeof(color));
        colorNum = 0;
        for(int i = 1; i <= m; i++)
            for(int j = 1; j <= n; j++){
                scanf(" %c",&grid[i][j]);
                if(grid[i][j]=='*') color[i][j]=-1; //把非油地带标记为-1
            }

        for(int i = 1; i <= m; i++)
            for(int j = 1; j <= n; j++)
                if(grid[i][j] == '@' && color[i][j]==0){
                    colorNum++;
                    Dfs(i,j);
                }
        printf("%d\n",colorNum);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值