LeetCode 133: Clone Graph
Posted keepshuatishuati
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 133: Clone Graph相关的知识,希望对你有一定的参考价值。
/** * 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 result = new UndirectedGraphNode(node.label); Queue<UndirectedGraphNode> queue = new LinkedList<>(); Map<UndirectedGraphNode, UndirectedGraphNode> connections = new HashMap<>(); connections.put(node, result); queue.offer(node); while (!queue.isEmpty()) { UndirectedGraphNode current = queue.poll(); for (UndirectedGraphNode neighbor : current.neighbors) { if (!connections.containsKey(neighbor)) { UndirectedGraphNode newNode = new UndirectedGraphNode(neighbor.label); connections.put(neighbor, newNode); queue.offer(neighbor); } connections.get(current).neighbors.add(connections.get(neighbor)); } } return result; } }
1. Create node when the neighbor is not found.
以上是关于LeetCode 133: Clone Graph的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 133. Clone Graph ----- java