首页 > 学院 > 开发设计 > 正文

LintCode Topological Sorting

2019-11-10 18:10:43
字体:
来源:转载
供稿:网友

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] …

出现了一个问题,hashset是存入和取出是没有规律的,但是这是有向图的问题,因此因该使用arraylist来进行记录

/** * 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); }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表