-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcycleValidation.js
75 lines (62 loc) · 2.31 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
63
64
65
66
67
68
69
70
71
72
73
74
75
//Storage -> 2D matrix (Basic needed)
let collectedGraphComponent = [];
let graphComponentMatrix = [];
// for (let i = 0; i < rows; i++) {
// let row = [];
// for (let j = 0; j < cols; j++) {
// //Why array -> more than 1 child relation (dependency)
// row.push([]);
// }
// graphComponentMatrix.push(row);
// }
//True -> cycle , False -> Not cyclic
function isGraphCyclic(graphComponentMatrix) {
//Dependency -> visited , dfsVisited (2D array)
let visited = []; // Node trace
let dfsVisited = []; // Stack trace
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) {
return [i,j];
}
}
}
}
return null;
}
//Start -> vis[TRUE] dfsVis(TRUE)
//END -> dfsVis(FALSE)
//IF vis[i][j](TRUE) --> already explored path, so go back to explore again
//Cycle detection condition -> if(vis[i][j]==true && dfsVis[i][j]==true ) -> cycle
function dfsCycleDetection(graphComponentMatrix, srcr, srcc, visited, dfsVisited) {
visited[srcr][srcc] = true;
dfsVisited[srcr][srcc] = true;
//A1-> [[0,1],[1,0],[5,10],...............]
for (let children = 0; children < graphComponentMatrix[srcr][srcc].length; children++) {
let [nbrr, nbrc] = graphComponentMatrix[srcr][srcc][children];
if (visited[nbrr][nbrc] === false) {
let response = dfsCycleDetection(graphComponentMatrix, nbrr, nbrc, visited, dfsVisited);
if (response === true) {
return true; //Found cycle so return immediately, no need to explore more path
}
}
else if (visited[nbrr][nbrc] === true && dfsVisited[nbrr][nbrc] === true) {
//Found cycle so return immediately ,no need to explore more path
return true;
}
}
dfsVisited[srcr][srcc] = false;
return false
}