-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcycleValidation.js
69 lines (61 loc) · 2.41 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
// Storage -> 2D array (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 -> cyclic, False -> Not cyclic
function isGraphCylic(graphComponentMatrix) {
// Dependency -> visited, dfsVisited (2D array)
let visited = []; // Node visit trace
let dfsVisited = []; // Stack visit 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);
// Found cycle so return immediately, no need to explore more path
if (response == true) return [i, j];
}
}
}
return null;
}
// Start -> vis(TRUE) dfsVis(TRUE)
// End -> dfsVis(FALSE)
// If vis[i][j] -> already explored path, so go back no use to explore again
// Cycle detection condition -> if (vis[i][j] == true && dfsVis[i][j] == true) -> cycle
// Return -> True/False
// True -> cyclic, False -> Not cyclic
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;
}