-
Notifications
You must be signed in to change notification settings - Fork 0
/
cycleValidation.js
62 lines (55 loc) · 1.68 KB
/
cycleValidation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Storage
let collectedGraphComponent = [];
let graphComponentMatrix = [];
// for(let i=0;i<rows;i++){
// let row = [];
// for(let j=0;j<cols;j++){
// row.push([]);
// }
// graphComponentMatrix.push(row);
// }
// True -> Cycle
function isGraphCyclic(graphComponentMatrix) {
// Dependenvy -> visited, dfsVisited (2D Array)
let visited = [];
let dfsVisited = [];
for(let i=0;i<rows;i++){
let visitedRow = [];
let dfsVisitedRow = [];
for(let j=0;j<cols;j++){
visitedRow.push(false);
dfsVisitedRow.push(false);
}
visited.push(visitedRow);
dfsVisited.push(dfsVisitedRow);
}
for(let i=0;i<rows;i++){
for(let j=0;j<cols;j++){
if(visited[i][j] === false){
let response = dfsCycleDetection(graphComponentMatrix, i, j, visited, dfsVisited);
if(response === true){
return [i,j];
}
}
}
}
return null;
}
function dfsCycleDetection(graphComponentMatrix, srcr, srcc, visited, dfsVisited){
visited[srcr][srcc] = true;
dfsVisited[srcr][srcc] = true;
for(let children = 0;children < graphComponentMatrix[srcr][srcc].length;children++){
let [crid,ccid] = graphComponentMatrix[srcr][srcc][children];
if(visited[crid][ccid] === false){
let response = dfsCycleDetection(graphComponentMatrix,crid,ccid,visited,dfsVisited);
if(response === true){
return true;
}
}
else if(dfsVisited[crid][ccid] === true){
return true;
}
}
dfsVisited[srcr][srcc] = false;
return false;
}