码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 133. Clone Graph, new code signature

时间:2020-05-03 13:09:50      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:深度克隆   code   ref   lin   copy   inf   sign   input   link   

克隆图。题意是给一个图中的某一个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

标签:深度克隆   code   ref   lin   copy   inf   sign   input   link   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12821312.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!