java 133.克隆图(BFS).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 133.克隆图(BFS).java相关的知识,希望对你有一定的参考价值。

/**
 * 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;
        Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
        return dfs(node, map);
    }
    
    private UndirectedGraphNode dfs(UndirectedGraphNode node, Map<UndirectedGraphNode, UndirectedGraphNode> map) {
        UndirectedGraphNode clone =  map.get(node);
        if (clone != null) {
            return clone;
        }
        clone = new UndirectedGraphNode(node.label);
        map.put(node, clone);
        for (UndirectedGraphNode c : node.neighbors) {
            clone.neighbors.add(dfs(c, map));
        }
        return clone;
    }
}
/**
 * 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;
        UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
        HashMap<Integer, UndirectedGraphNode> map = new HashMap<Integer, UndirectedGraphNode>(); //store visited nodes
        Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
        
        map.put(newNode.label, newNode);
        queue.offer(node);
        
        while(!queue.isEmpty()) {
            UndirectedGraphNode cur = queue.poll();
            
            for(UndirectedGraphNode neighbor : cur.neighbors) {
                if(!map.containsKey(neighbor.label)) {
                    map.put(neighbor.label, new UndirectedGraphNode(neighbor.label));
                    queue.add(neighbor);
                }
                map.get(cur.label).neighbors.add(map.get(neighbor.label));
            }
            
        }
        return newNode;
        
    }
}

以上是关于java 133.克隆图(BFS).java的主要内容,如果未能解决你的问题,请参考以下文章

java 133.克隆图(BFS).java

java 133.克隆图(BFS).java

java 133.克隆图(BFS).java

java 133.克隆图(BFS).java

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

LeetCode 133. 克隆图c++/java详细题解