JSFiddle - React, Tailwind, and code Playground
JavaScript
// has cycle
// Write a function, hasCycle, that takes in an object representing the adjacency list of a directed graph. The function should return a boolean indicating whether or not the graph contains a cycle.
const search = graph => {
const visited = new Set(); // Black
const nodes = Object.keys(graph);
for (let node of Object.keys(graph)) {
if (hasCycle(graph, node, visited)) {
return true;
}
}
return false;
};
const hasCycle = (graph, key, visited, visiting = new Set()) => {
// const key = Object.keys(node)[0];
console.log(`Visiting ${key}`);
//console.log(visiting);
// Base case 1: Have we visited this node yet? (CHECK BLACK and return false)
if (visited.has(key)) {
return false;
}
// Base case 2: Are we actively visiting this node? (CHECK GREY and return false)
if (visiting.has(key)) {
// We have a cycle.
return true;
}
// Otherwise, this is a new node, mark it as "visiting" (ADD GREY).
visiting.add(key);
// Recurse to connected nodes.
// const values = graph[key];
for(let neighbor of graph[key]){
if (hasCycle(graph, neighbor, visited, visiting)) {
return true;
}
}
// Move node from visiting to visited set.
visiting.delete(key);
visited.add(key);
// If no cycle, done.
return false;
};
// Determines if the prerequisite courses are possible by searching for a cycle in the adjacency graph.
const prereqsPossible = (numCourses, prereqs) => {
// Convert the prereqs array into a graph object.
const preGraph = prereqs.map(p => {
const result = {};
const key = p[0];
const value = p[1];
result[key] = value;
return result;
});
const graph = {};
preGraph.forEach(x => {
const key = Object.keys(x)[0] ;
const value = x[key];
graph[key] = graph[key] || [];
graph[key].push(value);
});
// Fill in any missing keys.
for (let i=0; i<numCourses; i++) {
if (!graph[i]) {
graph[i] = [];
}
}
...