One question of the day: 133. Clone picture

133. Clone graph

Wide search algorithm

1. Use a hash table visited to store all nodes that have been visited and cloned. The key in the hash table is the node in the original graph, and the value is the corresponding node in the clone graph.

2. Add the node given by the title to the queue. Clone the node and store it in the hash table.

3. Take out a node from the head of the queue each time, and traverse all neighboring points of the node. If a neighboring point has been visited, the neighboring point must be in visited, then the neighboring point is obtained from visited, otherwise, a new node is created and stored in visited, and the neighboring point is added to the queue. Add the cloned adjacency point to the adjacency list of the corresponding node in the clone graph. Repeat the above operations until the queue is empty, then the entire graph traversal ends.

/*
// 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 NULL;

        unordered_map<Node*, Node*> vis;
        queue<Node*> q;
        q.push(node);
        Node* clonenode = new Node(node->val);
        vis[node] = clonenode;

        while (!q.empty())
        {
            Node* tmp = q.front();
            q.pop();
            Node* clonetmp = vis[tmp];
            for (auto & neighbor:tmp->neighbors)
            {
                if (vis.find(neighbor)==vis.end())
                {
                    vis[neighbor] = new Node(neighbor->val);
                    q.push(neighbor);
                }
                clone.tmp->neighbors.push_back(vis[neighbor])
            }
            
        }
        return clonenode;

    }
};

 

Guess you like

Origin blog.csdn.net/hbhhhxs/article/details/107958940