I would like to check if a graph is cyclic in JavaScript. I have two arrays and each item in first array has a relation with (same index) item of second array.
Let's give an example: first = [4, 2, 3, 1]
second = [2, 3, 1, 4]
So there are relations between 4=>2, 2=>3, 3=>1 and 1=4. When you look at the graph, you can see that it is cyclic.
I wrote this code but it is returning false
although it should return true
for the following input;
first = [2, 1, 3, 4]
second = [3, 2, 1, 3]
How can I achieve this? Do I need to use graph algorithm?
function ifGraphCyclic(first, second) {
let nodes = new Map();
let unique = [];
for (let i = 0; i < first.length; i++) {
nodes.set(first[i], second[i]);
}
for (let value of nodes.values()) {
unique.push(nodes.get(value));
}
if (first.length === new Set(unique).size) {
return true;
}
return false;
}
console.log(ifGraphCyclic([4, 2, 3, 1], [2, 3, 1, 4])) // return true
console.log(ifGraphCyclic([2, 1, 3, 4], [3, 2, 1, 3])) // *return false but should return true*
console.log(ifGraphCyclic([1, 2, 2, 4, 4, 5, 6], [2, 3, 4, 5, 6, 6, 3])) // return false
console.log(ifGraphCyclic([1, 2, 2, 4, 5, 6, 6], [2, 3, 4, 5, 6, 3, 4])) // *return false but should return true*
question from:
https://stackoverflow.com/questions/66049922/how-to-check-if-a-graph-is-cyclic-in-javascript