leetcode题目
clone-graph
题目描述
* Clone an undirected graph. Each node in the graph
* contains a label and a list of its neighbors.
思路
* 1、递归实现
* 2、具体实现为:复制原节点,挂接邻居节点的复制节点到原节点的复制节点下
* 3、怎么复制邻居节点呢?递归调用复制原节点的函数
* 4、递归出口: 节点为null || 已经复制过该节点了
代码
package com.leetcode.graph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* 题目:
* 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#.
* First node is labeled as0. Connect node0to both nodes1and2.
* Second node is labeled as1. Connect node1to node2.
* Third node is labeled as2. Connect node2to node2(itself), thus forming a self-cycle.
* Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
*
*/
public class CloneGraph {
static class UndirectedGraphNode {
int label;
ArrayList<UndirectedGraphNode> neighbors;
UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
};
/**
* 思路:
* 1、递归实现
* 2、具体实现为:复制原节点,挂接邻居节点的复制节点到原节点的复制节点下
* 3、怎么复制邻居节点呢?递归调用复制原节点的函数
* 4、递归出口: 节点为null || 已经复制过该节点了
*/
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return node;
}
// Map中key不重写hashCode函数的话,默认使用Object的hashCode函数,比较的是对象的地址
// 而使用对象地址作为hashCode的值,符合此处的诉求,所以Node对象不需要重写hashCode、equals
Map<UndirectedGraphNode, UndirectedGraphNode> cache = new HashMap<>();
return cloneGraph(node,cache);
}
private UndirectedGraphNode cloneGraph(UndirectedGraphNode node, Map<UndirectedGraphNode, UndirectedGraphNode> cache) {
if (node == null) {
return null;
}
UndirectedGraphNode valueNode = cache.get(node);
if (valueNode != null) {
return valueNode;
}
// 复制节点本身
UndirectedGraphNode copy = new UndirectedGraphNode(node.label);
cache.put(node, copy);
// 复制邻居节点,并挂接到copy节点上
for (UndirectedGraphNode cur: node.neighbors) {
// 复制原节点的邻居节点挂接到复制节点的邻居列表中
copy.neighbors.add(cloneGraph(cur, cache));
}
// 返回复制节点
return copy;
}
public static void main(String[] args) {
UndirectedGraphNode root = new UndirectedGraphNode(0);
UndirectedGraphNode node1 = new UndirectedGraphNode(1);
UndirectedGraphNode node2 = new UndirectedGraphNode(2);
root.neighbors.add(node1);
node1.neighbors.add(node2);
UndirectedGraphNode newNode = new CloneGraph().cloneGraph(root);
System.out.println(newNode.label + "," + newNode.neighbors.get(0).label + ","
+ newNode.neighbors.get(0).neighbors.get(0).label);
}
}
参考:
【使用HashMap,如果key是自定义的类,就必须重写hashcode()和equals(),不重写会怎么样?】
【图的DFS与BFS】