Clone Graph -- leetcode
Clone an undirected graph. Each node in the graph containslabelAnd a list of itsneighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use
#As a separator for each node, and
,As a separator for node label and each neighbor of the node.
As an example, consider the serialized graph{0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated#.
- First node is labeled
0. Connect node0To both nodes1And2.
- Second node is labeled
1. Connect node1To node2.
- Third node is labeled
2. Connect node2To node2(Itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1 / \ / \ 0 --- 2 / \ \_/
A undirected connected graph must be copied.
Basic Ideas:
To traverse an image, take the breadth or depth first.
Repeat, remember the accessed nodes. Avoid repeated access. This function can be reused with the following map.
In addition, a map, ing, current node, and its corresponding replication node are required.
When accessing each node, You need to copy its adjacent edge. For the question, it is to copy its neighbors array.
If the node referenced by an edge does not exist, you need to create this node.
The following depth-first implementation methods. The actual execution time on leetcode is 72 ms.
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector
neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */class Solution {public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if (!node) return node; stack
s; unordered_map
m; s.push(node); auto root = new UndirectedGraphNode(node->label); m[node] = root; while (!s.empty()) { node = s.top(); s.pop(); auto node_copy = m[node]; for (auto neighbor: node->neighbors) { auto © = m[neighbor]; if (!copy) { s.push(neighbor); copy = new UndirectedGraphNode(neighbor->label); } node_copy->neighbors.push_back(copy); } } return root; }};
Breadth-first practice. The execution time on leetcode is 76 ms.
Replace the stack of the above algorithm with queue.
class Solution {public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if (!node) return node; queue
q; unordered_map
m; q.push(node); auto root_copy = new UndirectedGraphNode(node->label); m[node] = root_copy; while (!q.empty()) { node = q.front(); q.pop(); auto node_copy = m[node]; for (auto neighbor: node->neighbors) { auto © = m[neighbor]; if (!copy) { q.push(neighbor); copy = new UndirectedGraphNode(neighbor->label); } node_copy->neighbors.push_back(copy); } } return root_copy; }};