xxxxxxxxxx
class Pair {
constructor(node, par) {
this.node = node;
this.par = par;
}
}
class Sol {
adj = {};
vis = [];
dfsVis = [];
v = null;
constructor(v, edges) {
this.v = v;
this.vis = Array(v + 1).fill(false);
this.dfsVis = Array(v + 1).fill(false);
for (let edge of edges) {
const u = edge[0];
const v = edge[1];
if (!this.adj[u]) {
this.adj[u] = [];
}
this.adj[u].push(v);
}
console.log(this.adj);
}
detectCycle() {
for (let i = 1; i <= this.v; i++) {
if (this.vis[i] === false) {
if (this.isCycle(i, this.adj, this.vis, this.dfsVis) === true) {
console.log("Cycle Present");
return true;
}
}
}
console.log("Cycle Not Present");
return false;
}
isCycle(s, adj, vis, dfsVis) {
vis[s] = true;
dfsVis[s] = true;
if (adj[s]) {
for (let nbr of adj[s]) {
if (vis[nbr] === false) {
this.isCycle(nbr, adj, vis, dfsVis);
}
if (dfsVis[nbr]) {
return true;
}
}
}
dfsVis[s] = false;
return false;
}
}
const v = 7;
const edges = [
[1, 2],
[3, 4],
[2, 3],
[4, 1],
];
const s1 = new Sol(4, edges1);
s1.detectCycle();
xxxxxxxxxx
<script>
// A JavaScript Program to detect cycle in a graph
let V;
let adj=[];
function Graph(v)
{
V=v;
for (let i = 0; i < V; i++)
adj.push([]);
}
// This function is a variation of DFSUtil() in
// https://www.geeksforgeeks.org/archives/18212
function isCyclicUtil(i,visited,recStack)
{
// Mark the current node as visited and
// part of recursion stack
if (recStack[i])
return true;
if (visited[i])
return false;
visited[i] = true;
recStack[i] = true;
let children = adj[i];
for (let c=0;c< children.length;c++)
if (isCyclicUtil(children, visited, recStack))
return true;
recStack[i] = false;
return false;
}
function addEdge(source,dest)
{
adj.push(dest);
}
// Returns true if the graph contains a
// cycle, else false.
// This function is a variation of DFS() in
// https://www.geeksforgeeks.org/archives/18212
function isCyclic()
{
// Mark all the vertices as not visited and
// not part of recursion stack
let visited = new Array(V);
let recStack = new Array(V);
for(let i=0;i<V;i++)
{
visited[i]=false;
recStack[i]=false;
}
// Call the recursive helper function to
// detect cycle in different DFS trees
for (let i = 0; i < V; i++)
if (isCyclicUtil(i, visited, recStack))
return true;
return false;
}
// Driver code
Graph(4);
addEdge(0, 1);
addEdge(0, 2);
addEdge(1, 2);
addEdge(2, 0);
addEdge(2, 3);
addEdge(3, 3);
if(isCyclic())
document.write("Graph contains cycle");
else
document.write("Graph doesn't "
+ "contain cycle");
// This code is contributed by patel2127
</script>