[LeetCode] 133. Clone Graph, new code signature

Posted aaronliu1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 133. Clone Graph, new code signature相关的知识,希望对你有一定的参考价值。

克隆图。题意是给一个图中的某一个node的reference,请你深度克隆整个图。图中的每个节点包含他的值和邻接表。例子,

class Node {
    public int val;
    public List<Node> neighbors;
}

技术图片

 

 

Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Explanation: There are 4 nodes in the graph.
1st node (val = 1)‘s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)‘s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)‘s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)‘s neighbors are 1st node (val = 1) and 3rd node (val = 3).

思路是BFS。这个题也可以用DFS做但是我个人觉得BFS比较好记。具体的做法是创建一个visited hashmap记住<原来的node,新的node>之间的对应关系,和一个queue。

一开始,先把当前唯一的节点node加入queue并且把当前节点当做key存入hashmap,map的value是一个有着相同node.val但是只有一个空的邻接表(neighbors)的node;

然后从queue中开始弹出元素,每弹出一个元素cur,判断这个node的每一个邻居是否存在于hashmap,将不存在的邻居加入hashmap,同时也将这些刚刚加入hashmap中的邻居再次加入queue进行下一轮遍历;如果有某一个邻居已经存在于hashmap了,则往cur的邻接表里面添加这个已经存在的邻居的copy。

时间O(V + E)

空间O(n) - queue

Java实现

 1 /*
 2 // Definition for a Node.
 3 class Node {
 4     public int val;
 5     public List<Node> neighbors;
 6     
 7     public Node() {
 8         val = 0;
 9         neighbors = new ArrayList<Node>();
10     }
11     
12     public Node(int _val) {
13         val = _val;
14         neighbors = new ArrayList<Node>();
15     }
16     
17     public Node(int _val, ArrayList<Node> _neighbors) {
18         val = _val;
19         neighbors = _neighbors;
20     }
21 }
22 */
23 
24 class Solution {
25     public Node cloneGraph(Node node) {
26         // corner case
27         if (node == null) return null;
28 
29         // normal case
30         HashMap<Node, Node> visited = new HashMap<>();
31         Queue<Node> queue = new LinkedList<>();
32         queue.add(node);
33         visited.put(node, new Node(node.val, new ArrayList<>()));
34         while (!queue.isEmpty()) {
35             Node cur = queue.poll();
36             for (Node neighbor : cur.neighbors) {
37                 if (!visited.get(neighbor)) {
38                     visited.put(neighbor, new Node(neighbor.val, new ArrayList<>()));
39                     queue.offer(neighbor);
40                 }
41                 visited.get(cur).neighbors.add(visited.get(neighbor));
42             }
43         }
44     }
45 }

 

以上是关于[LeetCode] 133. Clone Graph, new code signature的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 133. Clone Graph

LeetCode 133: Clone Graph

LeetCode 133:克隆图 Clone Graph

leetcode 133. Clone Graph ----- java

[leetcode]133. Clone Graph 克隆图

Leetcode之广度优先搜索(BFS)专题-133. 克隆图(Clone Graph)