国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

LeetCode 133. Clone Graph

2019-11-10 18:42:30
字體:
供稿:網(wǎng)友

description: 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 / / /_/

這道題目因?yàn)橐稽c(diǎn)點(diǎn)的小bug,整整花了一個(gè)小時(shí)來debug。 在進(jìn)行node復(fù)制的時(shí)候,誤將代碼里的原有的node錯(cuò)誤的使用成了自己定義的root

/** * 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; } // find all node ArrayList<UndirectedGraphNode> arrayNode = findNode(node); // for (UndirectedGraphNode nodex : arrayNode) { // System.out.PRintln(nodex.label); // } // copy node Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>(); for (UndirectedGraphNode root : arrayNode) { map.put(root, new UndirectedGraphNode(root.label)); } //copy neighbors for (UndirectedGraphNode root : arrayNode) { UndirectedGraphNode roots = map.get(root); for (UndirectedGraphNode n : root.neighbors) { UndirectedGraphNode newNode = map.get(n); roots.neighbors.add(newNode); } } return map.get(node); } private ArrayList<UndirectedGraphNode> findNode(UndirectedGraphNode node) { Queue<UndirectedGraphNode> queue = new LinkedList<>(); Set<UndirectedGraphNode> set = new HashSet<>(); queue.offer(node); set.add(node); while (!queue.isEmpty()) { UndirectedGraphNode root = queue.poll(); for (UndirectedGraphNode roots : root.neighbors) { if (!set.contains(roots)) { queue.offer(roots); set.add(roots); } } } return new ArrayList<UndirectedGraphNode>(set); }}
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 高密市| 蒙自县| 阿城市| 青州市| 西峡县| 临澧县| 抚顺市| 隆化县| 阳东县| 新乐市| 军事| 禄劝| 喀什市| 嵩明县| 宝坻区| 新宾| 浙江省| 邵武市| 五华县| 钦州市| 犍为县| 洛隆县| 榕江县| 兴业县| 淮南市| 永宁县| 民丰县| 阿坝| 邮箱| 长汀县| 鲁山县| 太谷县| 克东县| 安徽省| 永福县| 卫辉市| 库尔勒市| 波密县| 开鲁县| 胶南市| 堆龙德庆县|