floodfill算法

floodfill算法先找到一个点,以这个点向周围填充或发散,将同一连通的区域或图染上同一种颜色。
这个算法可以看这里:http://lodev.org/cgtutor/floodfill.html#8-Way_Method_With_Stack

在无向图中求连通分量:

输入:

第一行包括n和m,代表n个点,m条边
11 10
0 1
0 2
1 2
1 3
2 3
4 5
4 6
7 8
8 9
8 10

图:

       0
     /  \          4          7
    1——2        / \         |
     \  /        5   6        8
      3                      / \
                            9   10

定义一个和图中点数一样大小的数组记录该点染成什么颜色,将同一连通分量染成一个颜色(即color[i]的值相等,不同颜色用不同数字表示)

那么每一个连通分量都将染成不同的颜色。

代码:

#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#include <cstdlib>

using namespace std;

class Graph
{
private:
    int n;
    int *color;
    vector<int> *edges;
public:
    Graph(int _n){
        n = _n;
        edges = new vector<int>[n];
        color = new int[n];
        memset(color, 0, n*sizeof(int));
    }
    ~Graph(){
        delete []color;
        delete []edges;
    }

    void myInsert(int x, int y){
        edges[x].push_back(y);
        edges[y].push_back(x);
    }

    void floodfill(){
        int current_color = 0;
        for(int i=0; i<n; i++){
            if(color[i]==0){
                current_color++;
                color[i]=current_color;
                queue<int> q;
                q.push(i);
                while(!q.empty()){
                    int tmp = q.front();
                    q.pop();
                    for(vector<int>::iterator it=edges[tmp].begin(); it!=edges[tmp].end(); it++){
                        if(color[*it]==0){
                            q.push(*it);
                            color[*it] = current_color;
                        }
                    }
                }

            }
        }
        for(int i=0; i<n; i++){
            cout<<"第"<<i<<"个点的颜色是:"<<color[i]<<endl;
        }
    }
};

int main(){
    int n, m;
    cin>>n>>m;
    Graph g(n);
    for(int i=0; i<m; i++){
        int x, y;
        cin>>x>>y;
        g.myInsert(x, y);
    }

    g.floodfill();

    system("pause");
    return 0;
}

如有错误麻烦指出,谢谢

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值