leetCode_Clone Graph

题意:克隆一个用邻接矩阵表示的无向图。无向图的数据结构以及函数原型如下:

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        
    }
};

解法:两遍BFS。第一遍把所有图的label找出来,用map<int,UndirectedGraphNode*>表示所有节点。第二遍把每个点的邻居找出来。要注意重边问题,不能再取队列的时候改变tag,要在放队列的时候改变tag,这样的话就能保证相同的节点不会被放2次。用tag蛮冗余的,其实再加邻居时,只要判断这个点的邻居是否为空就能保证不重复加邻居了。

代码如下:

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        int i,j;
        UndirectedGraphNode * temp;
        queue<UndirectedGraphNode *> nodeQueue;
        map<int,UndirectedGraphNode *> ans;
        if(node==NULL) return NULL;
        nodeQueue.push(node);
        while(!nodeQueue.empty())
        {
            temp=nodeQueue.front();
            nodeQueue.pop();
            ans[temp->label]=new UndirectedGraphNode(temp->label);
            for(i=0;i<temp->neighbors.size();i++)
                if(ans[temp->neighbors[i]->label]==NULL) nodeQueue.push(temp->neighbors[i]);
        }
        nodeQueue.push(node);
        while(!nodeQueue.empty())
        {
            temp=nodeQueue.front();
            nodeQueue.pop();
            if(ans[temp->label]->neighbors.size()==0)
            {
                for(i=0;i<temp->neighbors.size();i++)
                {
                    ans[temp->label]->neighbors.push_back(ans[temp->neighbors[i]->label]);
                    nodeQueue.push(temp->neighbors[i]);
                }
            }
        }
        return ans[node->label];
    }

};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值