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
/ \
\_/

Basically just clone the graph like clone a list in leetcode 138.

there are three ways t solve this (just traverse the graph and put new node into map)

/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
//dfs
Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node==null) return null;
//copy graph(deep copy), hashmap
map.put(node, new UndirectedGraphNode(node.label));
helper(node);
return map.get(node);
}
void helper(UndirectedGraphNode node){
for(int i = 0; i< node.neighbors.size(); i++){
UndirectedGraphNode neighbor = node.neighbors.get(i);
if(!map.containsKey(neighbor)){// not visited
UndirectedGraphNode newNode = new UndirectedGraphNode(neighbor.label);
map.put(neighbor, newNode);//visited
helper(neighbor);//why put helper here: where put stack where to recursive(update 1)
}
map.get(node).neighbors.add(map.get(neighbor)); //set the link of neighbors
}
}
}

Solution 2: bfs queue

/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node==null) return null;
//bfs
LinkedList<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
queue.offer(node);
Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>(); UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
map.put(node,newNode);
while(!queue.isEmpty()){
UndirectedGraphNode cur = queue.poll();//pop
for(int i = 0; i<cur.neighbors.size(); i++){
UndirectedGraphNode neighbor = cur.neighbors.get(i);
if(!map.containsKey(neighbor)){
queue.offer(neighbor);
newNode = new UndirectedGraphNode(neighbor.label);
map.put(neighbor, newNode);
map.get(cur).neighbors.add(newNode);
}
//if contains the key
else map.get(cur).neighbors.add(map.get(neighbor));
}
}
return map.get(node);
}
}

Solution 3: dfs with all node connected.

/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null) return null;
//dfs, if not visited, visited it and set it to visited, stack
LinkedList<UndirectedGraphNode> stack = new LinkedList<>();//add first
stack.push(node);
Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
map.put(node, newNode);
while(!stack.isEmpty()){
UndirectedGraphNode cur = stack.pop();//pop
for(int i = 0; i<cur.neighbors.size(); i++){
UndirectedGraphNode neighbor = cur.neighbors.get(i);//neighbor of current
if(!map.containsKey(neighbor)){//put neighbor into hashmap (visited)
newNode = new UndirectedGraphNode(neighbor.label);//copy neighbors
map.put(neighbor, newNode);
stack.push(neighbor);
}
//set the link of neighbors
map.get(cur).neighbors.add(map.get(neighbor)); } }
return map.get(node);
}
}
// relationship in hashmap
// key, value
// cur, map.get(cur)
// cur.neighbors, newNode/ map.get(eighbor)

What if nodes are not connnected partly: just write a loop to chekc all the node(call dfs for each node) in the graph

https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/

How do you represent the graph(one way from leetcode, another from geekforgeek)

Lastly: think about the time complexity of them

Graph 133. Clone Graph in three ways(bfs, dfs, bfs(recursive))的更多相关文章

  1. 133. Clone Graph 138. Copy List with Random Pointer 拷贝图和链表

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

  2. 【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 ...

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

  4. [LeetCode] 133. Clone Graph 克隆无向图

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

  5. 【LeetCode】133. Clone Graph 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目地址:https://le ...

  6. leetcode 133. Clone Graph ----- java

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

  7. 133. Clone Graph

    题目: Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. ...

  8. Java for LeetCode 133 Clone Graph

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

  9. 133. Clone Graph(图的复制)

    Given the head of a graph, return a deep copy (clone) of the graph. Each node in the graph contains ...

随机推荐

  1. idea中运行maven安装jar包到本地仓库跳过test

  2. unity下载资源存储-生成md5

    IEnumerator GetText() { using (UnityWebRequest request = UnityWebRequest.Get("localhost:80/txt/ ...

  3. h5移动端设置键盘搜索

    点击键盘上的搜索按钮实现页面跳转 <form action="#list?goods_title={{message?message:''}}" @submit.preven ...

  4. 移动端手势事件 hammer.JS插件

                      一.引入hammer.JS 1.下载地址:http://download.csdn.net/detail/webxiaoma/9872249 2.官网地址:http ...

  5. php对图片加水印--将图片先缩小,再在上面加水印

    方法: /**  * 图片加水印(适用于png/jpg/gif格式)  *  * @author flynetcn  *  * @param $srcImg  原图片  * @param $water ...

  6. iCheck

    iCheck改变 checkbox.radio的样式,原生或用bootstrap的都太丑. 简单用法:引用 <link rel="stylesheet" type=" ...

  7. Mysql插入Emoji表情出错

    Caused by: java.sql.SQLException: Incorrect at com.mysql.jdbc.SQLError.createSQLException(SQLError.j ...

  8. 数据结构(四)--- 红黑树(RedBlock-Tree)

      文章图片来自邓俊辉老师课件 先提几个问题去思考学习本文 : 红黑树和2-4树(B-Tree)很像,那么它存在的动机又是什么呢 插入和删除操作的逻辑又是怎么样的,时间和空间复杂度可以达到怎么样 和 ...

  9. asp.net Core2.1连接到Mysql 数据库

    1.首先,安装相关插件 在nuget下安装 1.Pomelo.EntityFrameworkCore.MySql 2.MySql.Data.EntityFrameworkCore 都要是2.1 < ...

  10. rabbit的fanout扇形交换机

    rabbit引入交换机概念. 交换机与生产者绑定. 队列与消费者绑定. 队列又与交换机绑定. 扇形交换机是  fanout类型的. 类似于其他消息中间件的 topic.一对多(生产者推送消息到指定交换 ...