L - Oil Deposits[涂色bfs]

L - Oil Deposits

题意:一个图上有好多好多油田,而这些油田可能是同一种油
以一个油田为中心,他所在的那个九宫格里若有其他油田,则认为这两者油是同一个油。
做法就是把整张图当作一个地图,把各个油田染上颜色。相同种类的油就是同一种颜色。

struct node {
    int x,y;
};
char map[len][len];
int vis[len][len], vis_arr[len*len];//前面这个数组涂色,后面这个数组找出现过的颜色
int dv[8][2] = {{0,-1},{0,1},{-1,0},{1,0},{1,-1},{-1,1},{1,1},{-1,-1}};
//九宫格 八个方向
int color = 1, n, m, color_num = 0;//涂色 最后数颜色数量
queue <struct node> q;
struct node head;
int main(){
    while (cin >> n >> m) {
        if (n == 0 || m == 0) break;
        
        Init();
        bfs();
        
        for (int i=0; i<n; i++){//找颜色
            for (int j=0; j<m; j++){
                if (vis[i][j] !=0  && vis_arr[vis[i][j]] == 0){
                    vis_arr[vis[i][j]] ++;
                    color_num ++;
                }
            }
        }
        cout << color_num << endl;
    }
    
    return 0;
}
void Init(){
    memset(map, '.', sizeof(map));
    memset(vis, 0, sizeof(vis));
    memset(vis_arr, 0, sizeof(vis_arr));
    color = 1;color_num = 0;
    
    for (int i=0; i<n; i++){
        for (int j=0; j<m; j++){
            cin >> map[i][j];
        }
    }
}
void bfs(){
    for (int i=0; i<n; i++){
        for (int j=0; j<m; j++){
            if (map[i][j] == '@'){//找油田涂色
                paint(i,j);
            }
        }
    }
}
void paint(int x, int y){
    struct node tmp;
    tmp.x = x; tmp.y = y;
    q.push(tmp);
    //先不管三七二十一,入队
    while (!q.empty()) {
        head = q.front();
        q.pop();
        
        if (vis[x][y] == 0)//没上过色的说明这块风水宝地还没有划过区域
            vis[x][y] = color;
        
        for (int i=0; i<8; i++){
            int _x = head.x + dv[i][0];
            int _y = head.y + dv[i][1];
            
            if (map[_x][_y] != '@') continue;
            if (vis[_x][_y] != 0) continue;
            if (_x<0 || _x>=n || _y<0 || _y>=m) continue;
            
            vis[_x][_y] = vis[x][y];//和上个油田涂上相同颜色
            struct node t;
            t.x = _x; t.y = _y;
            q.push(t);//入队 找下个
        }
    }
    color++;//换颜色
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值