Clone Graph Leetcode
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
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 by #.
- First node is labeled as
0. Connect node0to both nodes1and2. - Second node is labeled as
1. Connect node1to node2. - Third node is labeled as
2. Connect node2to node2(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
这道题可以用BFS.
要注意:
clone的时候,指向的点也要是新建的点,不可指向原来的点;
返回的点要是原来的node所复制出来的点。
/** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * List<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } * }; */ public class Solution { public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if (node == null) { return null; } Map<Integer, UndirectedGraphNode> hm = new HashMap<>(); Queue<UndirectedGraphNode> q = new LinkedList<>(); q.add(node); UndirectedGraphNode clone = new UndirectedGraphNode(node.label); hm.put(node.label, clone); UndirectedGraphNode tmp = null; while (!q.isEmpty()) { UndirectedGraphNode no = q.poll(); tmp = hm.getOrDefault(no.label, new UndirectedGraphNode(no.label)); for (UndirectedGraphNode n : no.neighbors) { UndirectedGraphNode cloneN = null; if (hm.containsKey(n.label)) { cloneN = hm.get(n.label); } else { cloneN = new UndirectedGraphNode(n.label); q.add(n); hm.put(n.label, cloneN); } tmp.neighbors.add(cloneN); } } return clone; } }
开心的是和top solution思路一样,还是按照他们的改了一下,虽然我觉得我的思路最清晰了。。。
期间发现不用getOrDefault因为一定会有。
public class Solution { public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if (node == null) { return null; } Map<Integer, UndirectedGraphNode> hm = new HashMap<>(); Queue<UndirectedGraphNode> q = new LinkedList<>(); q.add(node); UndirectedGraphNode clone = new UndirectedGraphNode(node.label); hm.put(node.label, clone); while (!q.isEmpty()) { UndirectedGraphNode no = q.poll(); for (UndirectedGraphNode n : no.neighbors) { if (!hm.containsKey(n.label)) { q.add(n); hm.put(n.label, new UndirectedGraphNode(n.label)); } hm.get(no.label).neighbors.add(hm.get(n.label)); } } return clone; } }
DFS以后再写吧。。。。到时候再回顾。。。

浙公网安备 33010602011771号