BFS:克隆圖

BFS:克隆圖

問題:

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

思路:

首先建立與原圖節點個數相等的新節點,然後按照原圖中邊的連接規則,對新圖中對應節點進行連接

在建立新節點的過程中用map保存新節點與原節點的映射關係

首先使用BFS遍歷所有節點,每遍歷到一個節點,創建一個與之對應的新節點,並用map保存它們的映射關係

遍歷map中所有的原圖節點,找到它的鄰接點數組,遍歷該數組,按照原連接規則將新圖的對應節點相連

代碼:

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> neighbors;
    
    Node() {
        val = 0;
        neighbors = vector<Node*>();
    }
    
    Node(int _val) {
        val = _val;
        neighbors = vector<Node*>();
    }
    
    Node(int _val, vector<Node*> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
};
*/

class Solution {
public:
    Node* cloneGraph(Node* node) {
        if( node==NULL )
            return node;
        unordered_map< Node*,Node* > table;
        queue<Node*> q;
        q.push( node );
        while( q.size()!=0 )
        {
            Node* temp=q.front();
            q.pop();
            Node* p=new Node( temp->val,{} );
            table[ temp ]=p;
            for( Node* adj : temp->neighbors )
            {
                if( table.find( adj )==table.end() )
                    q.push( adj );
            }
        }
        auto i=table.begin();
        for( ;i!=table.end();i++ )
        {
            for( auto temp:i->first->neighbors )
            {
                i->second->neighbors.push_back( table.find( temp )->second );
            }
        }
        return table.find(node)->second;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章