Saturday, March 19, 2022

Leet Code 210. Course Schedule II - Kahn's Algorithm

https://leetcode.com/problems/course-schedule-ii/


Here we need to print the topological sort using Kahn's Algo



package pep.Day44;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class LeetCode_210_Course_Schedule_II {
public static void main(String[] args) {
System.out.println(findOrder(2, new int[][]{{1, 0}}));
}

public static int[] findOrder(int n, int[][] pre) {
ArrayList<Integer>[] graph = new ArrayList[n];

for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}

int[] indegree = new int[n];

for (int[] p : pre) {
graph[p[0]].add(p[1]);
indegree[p[1]]++;
}

Queue<Integer> que = new LinkedList<>();

for (int i = 0; i < n; i++)
if (indegree[i] == 0)
que.add(i);

int[] ansArr = new int[n];
int idx = -1;
while (!que.isEmpty()) {
int out = que.remove();
ansArr[n - 1 - (++idx)] = out;
for (int nbr : graph[out]) {
if (--indegree[nbr] == 0)
que.add(nbr);
}
}

return idx < n - 1 ? new int[0] : ansArr;

}
}




No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...