【leetcode】Clone Graph

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 #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:

       1
      /      /       0 --- 2
         /          \_/


题解:利用DFS递归的方法克隆图,用hashmap保存原图中的节点和新图中的节点的对应关系。而且利用这个hashmap可以在O(1)的时间内判断一个节点是否被克隆过,并且知道克隆它得到的新节点。

实现一个克隆节点的方法,在这个方法中:

  1. 判断这个节点是否被clone过了,如果是,返回它对应的clone节点;
  2. 如果没有被clone过,那么新建节点为该节点的clone节点,并且递归的clone它的邻居节点,放入该节点的neighbors列表里面;

代码如下:

 1 /**
 2  * Definition for undirected graph.
 3  * class UndirectedGraphNode {
 4  *     int label;
 5  *     List<UndirectedGraphNode> neighbors;
 6  *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 7  * };
 8  */
 9 public class Solution {
10     private HashMap<UndirectedGraphNode,UndirectedGraphNode> mapClone = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
11
12     private UndirectedGraphNode cloneNode(UndirectedGraphNode node){
13         if(node == null)
14             return null;
15         //if this node already has a clone
16         if(mapClone.containsKey(node))
17             return mapClone.get(node);
18
19         //if this node hasn‘t been cloned, we construct a new node copy
20         UndirectedGraphNode copy = new UndirectedGraphNode(node.label);
21         mapClone.put(node, copy);
22
23         //clone all the neighbers of node
24         for(UndirectedGraphNode n:node.neighbors){
25             copy.neighbors.add(cloneNode(n));
26         }
27         return copy;
28     }
29     public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
30         return cloneNode(node);
31     }
32 }

【leetcode】Clone Graph

时间: 2024-08-07 12:30:39

【leetcode】Clone Graph的相关文章

【leetcode】Clone Graph(python)

类似于二叉树的三种遍历,我们可以基于遍历的模板做很多额外的事情,图的两种遍历,深度和广度模板同样也可以做很多额外的事情,这里举例利用深度优先遍历的模板来进行复制,深度优先中,我们先访问第一个结点,接着访问第一个邻接点,再访问邻节点的邻节点.... class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): if None =

【LeetCode】Clone Graph 解题报告

[题目] 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

【LeetCode】Clone Graph (2 solutions)

Clone Graph 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 an

【Leetcode】 Clone Graph

题目链接:https://leetcode.com/problems/clone-graph/ 题目: 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

【LeetCode】BFS(共43题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [101]Symmetric Tree 判断一棵树是不是对称. 题解:直接递归判断了,感觉和bfs没有什么强联系,当然如果你一定要用queue改写的话,勉强也能算bfs. // 这个题目的重点是 比较对象是 左子树的左儿子和右子树的右儿子, 左子树的右儿子和右子树的左儿子.不要搞错. // 直接中序遍历的话会有错的情况,最蠢的情况是数字标注改一改.. 1 /** 2

【LeetCode】深搜DFS(共85题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [98]Validate Binary Search Tree [99]Recover Binary Search Tree [100]Same Tree [101]Symmetric Tree [104]Maximum Depth of Binary Tree [105]Construct Binary Tree from Preorder and Inorder

【leetcode】Generate Parentheses

题目: 给定整数n,返回n对匹配的小括号字符串数组. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 分析: 这种问题的模式是:1)问题的解有多个 ,2)每个解都是由多个有效的 "步骤" 组成的,3)变更以有解的某个或某些"步骤"

【LeetCode】Implement strStr()

Implement strStr() Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 标准KMP算法.可参考下文. http://blog.csdn.net/yaochunnian/article/details/7059486 核心思想在于求出模式串前缀与后缀中重复部分,将重复信息保存在n

【LeetCode】Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 ->