From the course: Data Structures in JavaScript: Trees and Graphs
Unlock this course with a free trial
Join today to access over 25,500 courses taught by industry experts.
Solution: Course scheduling
From the course: Data Structures in JavaScript: Trees and Graphs
Solution: Course scheduling
(bright music) - [Instructor] In this lesson, we're solving the course scheduling problem, where we're given a list of course prerequisites and asked to determine any valid order to take them. We tackle this by building an adjacency list and performing a topologicalSort(). This topologicalSort() function takes in a graph represented as an edge list, which is a list of from to prerequisite pairs. We start by representing each course as a node. Each node contains its name and a list of other courses that depend on it. It's children. To build our course, we initialize three things: nodes, an adjacency lists to represent our graph, sorted, a list that will eventually hold the final course order and visited a set to keep track of nodes we've already visited. Here's how we'll construct the first few lines of our function. Now, we'll loop through all the edges, each pair of courses, and create the corresponding nodes if they don't already exist. This step ensures that for each from to pair…