# Topological Sorting

{% embed url="<https://www.lintcode.com/problem/127/>" %}

## Solution 1 (Java)

```java
/**
 * Definition for Directed graph.
 * class DirectedGraphNode {
 *     int label;
 *     List<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) {
        ArrayList<DirectedGraphNode> res = new ArrayList<>();
        Map<DirectedGraphNode, Integer> inDegree = new HashMap<>();
        for (DirectedGraphNode n : graph) {
            for (DirectedGraphNode nei : n.neighbors) {
                if (inDegree.containsKey(nei)) {
                    inDegree.put(nei, inDegree.get(nei) + 1);
                } else {
                    inDegree.put(nei, 1);
                }
            }
        }

        Queue<DirectedGraphNode> q = new ArrayDeque<>();
        for (DirectedGraphNode n : graph) {
            if (!inDegree.containsKey(n)) {
                q.offer(n);
            }
        }

        while (!q.isEmpty()) {
            DirectedGraphNode curr = q.poll();
            res.add(curr);
            for (DirectedGraphNode nei : curr.neighbors) {
                inDegree.put(nei, inDegree.get(nei) - 1);
                if (inDegree.get(nei) == 0) {
                    q.offer(nei);
                }
            }
        }

        return res;
    }
}
```

### Notes

* It is important to keep track of the in-degree of the nodes.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.yushunchen.com/algo/bfs/2.-connected-graph-and-topologic-sorting/topological-sorting.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
