import java.util.*;

/**
* Source : https://oj.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, 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 node 0 to both nodes 1 and 2.
* Second node is labeled as 1. Connect node 1 to node 2.
* 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
* / \
* \_/
*
*/
public class CloneGraph { /**
* 克隆无向图
*
* 使用BFS或者DFS
*
* HashMap用来记录已经被克隆过的node
* key:被克隆过的node
* value:由key克隆出来的node
*
* @param node
* @return
*/
public UndirectedGraphNode clone (UndirectedGraphNode node) {
if(node == null) {
return null;
}
Queue<UndirectedGraphNode> queue = new ArrayDeque<UndirectedGraphNode>();
Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
map.put(node, new UndirectedGraphNode(node.label));
queue.offer(node);
while (queue.size() > 0) {
UndirectedGraphNode cur = queue.poll();
UndirectedGraphNode cloneNode = map.get(cur);
if (cloneNode.neighbors == null) {
cloneNode.neighbors = new ArrayList<UndirectedGraphNode>();
}
if (cur.neighbors == null) {
continue;
}
for (UndirectedGraphNode neighbor : cur.neighbors) {
if (map.containsKey(neighbor)) {
cloneNode.neighbors.add(map.get(neighbor));
} else {
UndirectedGraphNode temp = new UndirectedGraphNode(neighbor.label);
cloneNode.neighbors.add(temp);
map.put(neighbor, temp);
queue.offer(neighbor);
}
}
} return map.get(node);
} /**
*
* 根据字符串创建图的方法不对。。。待完善
* @param graphSrt
* @return
*/
public static UndirectedGraphNode createGraph (String graphSrt) {
if (graphSrt == null || graphSrt.length() == 0) {
return null;
}
Map<Integer, UndirectedGraphNode> map = new HashMap<Integer, UndirectedGraphNode>();
String[] nodeStrs = graphSrt.split("#");
UndirectedGraphNode first = null;
for (int i = 0; i < nodeStrs.length; i++) {
String[] nodeArr = nodeStrs[i].split(",");
UndirectedGraphNode node = null;
for (int j = 0; j < nodeArr.length; j++) {
Integer label = Integer.parseInt(nodeArr[j]); if (j == 0) {
if (map.containsKey(label)) {
node = map.get(label);
} else {
node = new UndirectedGraphNode(label);
map.put(label, node);
}
if (first == null) {
first = node;
}
} else {
UndirectedGraphNode neighbor = null;
if (map.containsKey(label)) {
neighbor = map.get(label);
} else {
neighbor = new UndirectedGraphNode(label);
map.put(label, neighbor);
}
if (node.neighbors == null) {
node.neighbors = new ArrayList<UndirectedGraphNode>();
}
if (neighbor.label == node.label) {
neighbor = new UndirectedGraphNode(label);
}
node.neighbors.add(neighbor);
}
}
}
return first;
} public static void print (UndirectedGraphNode node) {
if (node == null) {
return;
}
StringBuffer buffer = new StringBuffer();
Queue<UndirectedGraphNode> queue = new ArrayDeque<UndirectedGraphNode>();
queue.offer(node);
while (queue.size() > 0) {
UndirectedGraphNode cur = queue.poll();
buffer.append(cur.label);
for (UndirectedGraphNode neighbor : cur.neighbors) {
buffer.append(",");
buffer.append(neighbor.label);
queue.offer(neighbor);
}
buffer.append("#");
}
if (buffer.length() > 0) {
buffer.deleteCharAt(buffer.length()-1);
}
System.out.println(buffer);
} private static class UndirectedGraphNode {
int label;
List<UndirectedGraphNode> neighbors; public UndirectedGraphNode(int label) {
this.label = label;
}
} public static void main(String[] args) {
CloneGraph cloneGraph = new CloneGraph();
String graphStr = "0,1,2#1,2#2,2";
print(cloneGraph.clone(createGraph(graphStr)));
}
}

leetcode — clone-graph的更多相关文章

  1. LeetCode: Clone Graph 解题报告

    Clone GraphClone an undirected graph. Each node in the graph contains a label and a list of its neig ...

  2. [LeetCode] Clone Graph 无向图的复制

    Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...

  3. [LeetCode] Clone Graph 克隆无向图

    Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph ...

  4. LeetCode:Clone Graph

    题目如下:实现克隆图的算法  题目链接 Clone an undirected graph. Each node in the graph contains a label and a list of ...

  5. [leetcode]Clone Graph @ Python

    原题地址:https://oj.leetcode.com/problems/clone-graph/ 题意:实现对一个图的深拷贝. 解题思路:由于遍历一个图有两种方式:bfs和dfs.所以深拷贝一个图 ...

  6. [Leetcode Week3]Clone Graph

    Clone Graph题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/clone-graph/description/ Description Clon ...

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

    Leetcode之广度优先搜索(BFS)专题-133. 克隆图(Clone Graph) BFS入门详解:Leetcode之广度优先搜索(BFS)专题-429. N叉树的层序遍历(N-ary Tree ...

  8. [LeetCode]Copy List with Random Pointer &amp;Clone Graph 复杂链表的复制&amp;图的复制

    /** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label ...

  9. 【LeetCode】133. Clone Graph (3 solutions)

    Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of its nei ...

  10. 21. Clone Graph

    Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of its nei ...

随机推荐

  1. 2018-2019-2 网络对抗技术 20162329 Exp5 MSF基础应用

    目录 Exp5 MSF基础应用 一.基础问题回答 二.攻击系统 ms08_067攻击(成功) 三.攻击浏览器 ms11_050_mshtml_cobjectelement(Win7失败) 手机浏览器攻 ...

  2. h5、css3基础

    一.html(超文本标记语言) 作用:实现页面布局 页面由许多标记符号组成 由浏览器解释执行 二.html主题创建方式 !(英文状态)+tab html:4s+tab html:5+tab 三.标签 ...

  3. h5唤起APP并检查是否成功

    // 检查app是否打开 function checkOpen(cb) { const clickTime = +(new Date()); function check(elsTime) { if ...

  4. Java_Object

    说一下java中的Object类. 1.Object: Object是java类库中的一个特殊类,也是所有类的父类. Object类定义了一些有用的方法,由于是根类,这些方法在其他类中都存在,一般是进 ...

  5. JavaScript / 本地存储

    cookie 首先让我们先了解一下,什么是cookie,cookie是浏览器提供的一种机制,他将document.cookie的接口提供给JavaScript使其可以对cookie进行控制,但cook ...

  6. html+css手机端自动适应

    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scal ...

  7. mongodb远程数据库的连接以及备份导入导出数据

    环境win10; 运行cmd cd到目录mongodb的bin目录: 连接远程mongodb: 连接命令:mongo -u username -p pwd host:post/database(数据库 ...

  8. spring MVC 的MultipartFile转File读取

    转自:http://www.cnblogs.com/hahaxiaoyu/p/5102900.html 第一种方法:   MultipartFile file = xxx;         Commo ...

  9. [Swift]LeetCode757. 设置交集大小至少为2 | Set Intersection Size At Least Two

    An integer interval [a, b] (for integers a < b) is a set of all consecutive integers from ato b, ...

  10. 交叉编译 tcpdump

    目录 1. 下载 tcpdump 2. 交叉编译 3. 相关说明 1. 下载 tcpdump 官网:http://www.tcpdump.org/ 2. 交叉编译 交叉编译libpcap: $ wge ...