C++ solution easy to understand


  • 0
    L
    class Solution {
    private:
    	unordered_map<int, UndirectedGraphNode *> labelSets;
    public:
    	void createNode(UndirectedGraphNode *node) {
    		if (node == NULL)
    			return;
    		if (this->labelSets.find(node->label) != this->labelSets.end()) {
    			return;
    		}
    		UndirectedGraphNode * cur = new UndirectedGraphNode(node->label);
    		this->labelSets[cur->label] = cur;
    
    		for (int i = 0; i < (int) node->neighbors.size(); i++) {
    			createNode(node->neighbors[i]);
    		}
    	}
    	UndirectedGraphNode *dfs(UndirectedGraphNode *node) {
    		UndirectedGraphNode * ret = NULL;
    		if (node == NULL)
    			return ret;
    		ret = labelSets[node->label];
    		if (ret->neighbors.size()!=0) {
    			return ret;
    		}
    		
    		for (int i = 0; i < (int) node->neighbors.size(); i++) {
    			UndirectedGraphNode * o = node->neighbors[i];
    			UndirectedGraphNode * n = this->labelSets[o->label];
    			ret->neighbors.push_back(n);
    		}
    		for (int i = 0; i < (int) node->neighbors.size(); i++) {
    			dfs(node->neighbors[i]);
    		}
    		return ret;
    	}
    	UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
    		if (node == NULL)
    			return NULL;
    		this->labelSets.clear();
    		createNode(node); //create nodes
    		
    		return dfs(node);//set neighors
    	}
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.