133. clone graph

来源:互联网 发布:重生之娱乐网络帝国 编辑:程序博客网 时间:2024/06/03 20:31

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


克隆图,感觉是被题目中的list给误导了。实际解题跟list也没什么关系;

给了一个类 类的对象中有neighbor成员变量 表示与它相邻的节点 同时 每个node是有编号的。

开始递归判断就可以了,开始节点的邻节点是否已经加到map中了加了的话直接返回这个节点,没加的话把这个节点put到map中,并把这个节点记录下来再继续找这个节点的临界点 递归查找


/** * Definition for undirected graph. * class UndirectedGraphNode { *     int label; *     List<UndirectedGraphNode> neighbors; *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } * }; */public class Solution {    HashMap<Integer,UndirectedGraphNode> map=new HashMap<>();    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {        if(node==null) return node;        if(map.containsKey(node.label))            return map.get(node.label);        UndirectedGraphNode clone=new UndirectedGraphNode(node.label);        map.put(clone.label,clone);                for(UndirectedGraphNode neighbor:node.neighbors)            clone.neighbors.add(cloneGraph(neighbor));                return clone;    }}


BFS  

遍历的时候把 node的所有邻居放进去, 遍历完这一层之后再继续遍历刚放进去的节点继续 

类里面的关系要搞清楚,label对应一个UndirectedGraphNode(label)

public class Solution {       public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {        if(node==null) return node;         HashMap<Integer,UndirectedGraphNode> map=new HashMap<>();         Queue<UndirectedGraphNode> queue=new LinkedList<>();         queue.offer(node);         map.put(node.label,new UndirectedGraphNode(node.label));                  while(!queue.isEmpty()){             UndirectedGraphNode oldNode=queue.poll();             for(UndirectedGraphNode noden: oldNode.neighbors){  //noden都是oldNode的邻居 需要加进去,遍历是为了找出相关联的节点                 if(!map.containsKey(noden.label)){                     queue.offer(noden);                     map.put(noden.label,new UndirectedGraphNode(noden.label));                 }                 map.get(oldNode.label).neighbors.add(map.get(noden.label));             }         }         return map.get(node.label);           }}


0 0