|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int N, M; |
| 7 | + static List<Integer>[] graph; |
| 8 | + static int[] indegree; |
| 9 | + public static void main(String[] args) throws IOException { |
| 10 | + input(); |
| 11 | + getIndegree(); |
| 12 | + List<Integer> order = topologySort(); |
| 13 | + for (int num : order) { |
| 14 | + System.out.print(num + " "); |
| 15 | + } |
| 16 | + System.out.println(); |
| 17 | + } |
| 18 | + |
| 19 | + static ArrayList<Integer> topologySort() { |
| 20 | + ArrayList<Integer> orderList = new ArrayList<>(); // 정점의 방문 순서 |
| 21 | + Queue<Integer> q = new ArrayDeque<>(); |
| 22 | + for (int i = 1; i < N+1; i++) { |
| 23 | + if (indegree[i] == 0) { |
| 24 | + q.offer(i); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + while (!q.isEmpty()) { |
| 29 | + int node = q.poll(); |
| 30 | + orderList.add(node); |
| 31 | + for (int next : graph[node]) { |
| 32 | + if (--indegree[next] == 0) q.offer(next); |
| 33 | + } |
| 34 | + } |
| 35 | + return orderList; |
| 36 | + } |
| 37 | + |
| 38 | + static void getIndegree() { |
| 39 | + indegree = new int[N+1]; |
| 40 | + for (int from = 1; from < N+1; from++) { |
| 41 | + for (int to : graph[from] ){ |
| 42 | + // 진입 차수 기록 |
| 43 | + indegree[to]++; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + static void input() throws IOException { |
| 49 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 50 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 51 | + N = Integer.parseInt(st.nextToken()); |
| 52 | + M = Integer.parseInt(st.nextToken()); |
| 53 | + graph = new List[N+1]; |
| 54 | + for (int i = 1; i < N+1; i++) { |
| 55 | + graph[i] = new ArrayList<>(); |
| 56 | + } |
| 57 | + for (int i = 0; i < M; i++) { |
| 58 | + st = new StringTokenizer(br.readLine()); |
| 59 | + int a = Integer.parseInt(st.nextToken()); |
| 60 | + int b = Integer.parseInt(st.nextToken()); |
| 61 | + graph[a].add(b); |
| 62 | + } |
| 63 | + br.close(); |
| 64 | + |
| 65 | + } |
| 66 | +} |
| 67 | +``` |
0 commit comments