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

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

LintCode Topological Sorting

2019-11-10 20:22:07
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

description: Given an directed graph, a topological order of the graph nodes is defined as follow:

For each directed edge A -> B in graph, A must before B in the order list. The first node in the order can be any node in the graph with no nodes direct to it. Find any topological order for the given graph.

Notice

You can assume that there is at least one topological order in the graph.

Have you met this question in a real interview? Yes Clarification Learn more about rePResentation of graphs

Example For graph as follow:

picture

The topological order can be:

[0, 1, 2, 3, 4, 5] [0, 2, 3, 1, 5, 4] …

出現(xiàn)了一個(gè)問(wèn)題,hashset是存入和取出是沒(méi)有規(guī)律的,但是這是有向圖的問(wèn)題,因此因該使用arraylist來(lái)進(jìn)行記錄

/** * Definition for Directed graph. * class DirectedGraphNode { * int label; * ArrayList<DirectedGraphNode> neighbors; * DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); } * }; */public class Solution { /** * @param graph: A list of Directed graph node * @return: Any topological order for the given graph. */ public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) { // write your code here if (graph == null) { return null; } Map<DirectedGraphNode, Integer> map = new HashMap<>(); for (DirectedGraphNode node : graph) { for (DirectedGraphNode root : node.neighbors) { if (map.containsKey(root)) { map.put(root, map.get(root) + 1); } else { map.put(root, 1); } } } Queue<DirectedGraphNode> queue = new LinkedList<>(); ArrayList<DirectedGraphNode> set = new ArrayList<>(); for (DirectedGraphNode node : graph) { if(!map.containsKey(node)) { set.add(node); queue.offer(node); } } while (!queue.isEmpty()) { DirectedGraphNode root = queue.poll(); for (DirectedGraphNode node : root.neighbors) { map.put(node, map.get(node) - 1); if (map.get(node) == 0) { queue.offer(node); set.add(node); } } } return new ArrayList<DirectedGraphNode>(set); }}
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 尼木县| 桓台县| 铁力市| 武清区| 大埔区| 定南县| 扬中市| 晋州市| 汝南县| 陕西省| 启东市| 嘉禾县| 壤塘县| 穆棱市| 蒙自县| 新邵县| 南通市| 柳州市| 慈溪市| 台南市| 南澳县| 合川市| 长兴县| 定襄县| 登封市| 大石桥市| 景泰县| 额济纳旗| 育儿| 饶河县| 南城县| 衡南县| 湛江市| 长丰县| 吴旗县| 霍邱县| 沈阳市| 丹江口市| 扎鲁特旗| 新平| 平山县|