Cycle in Graph -

  • just checking there is a cycle

/*
0: white => not yet
1: grey => in traversing a graph
2: black => completed
*/

function cycleInGraph(edges) {
  const hasCycle = dfsAll(edges);
  
  return hasCycle;
}

function dfsAll(adjacencyList) {
  const visited = new Array(adjacencyList.length).fill(0);
  
  for (let i = 0; i < adjacencyList.length; i++) {
    const vertex = i;
    if (visited[vertex] !== 0) continue;
    if (visited[vertex] === 2) continue; 
		// either is fine
    
    const hasCycle = dfs(adjacencyList, vertex, visited);
    console.log({
      visited
    })
    if (hasCycle === true) return true;
  }
  
  return false;
}

function dfs(adjacencyList, here, visited) {
  visited[here] = 1;

  const edges = adjacencyList[here];
  for (let i = 0; i < edges.length; i++) {
    const there = edges[i];
    
    if (visited[there] === 1) return true;
    if (visited[there] === 2) continue;
    const hasCycle = dfs(adjacencyList, there, visited);
    if (hasCycle === true) return true;
  }

  visited[here] = 2;
  return false;
}

// Do not edit the line below.
exports.cycleInGraph = cycleInGraph;
  • v + e, v

  • with everything

Last updated