-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgraph_algorithm.js
More file actions
82 lines (69 loc) · 2.35 KB
/
Copy pathgraph_algorithm.js
File metadata and controls
82 lines (69 loc) · 2.35 KB
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
76
77
78
79
80
81
82
(function() {
var WHITE = 0
var GRAY = 1
var BLACK = 2
var GraphAlgorithm = {
/**
* Detects loops in a directed graph using a graph coloring algorithm.
*
* @param {Array} vertices - An array of vertices. Each vertex can be either
* an integer or a string.
* @param {Array} edges - An array of edges. Each edge is represented as an array of length 2,
* specifying the source and destination vertices. Format: [source, destination].
*
* @returns {Object} An object indicating whether a loop is present and, if so, the vertices
* forming the loop. The return value has the following structure:
* - hasLoop: A boolean value indicating whether a loop is present in the graph.
* - loop: An array of vertices forming the loop, listed in the order they are encountered
* during traversal.
*/
hasLoop: function(vertices, edges) {
var colors = {}
var path = []
// Initialize colors to white
for (var i=0; i<vertices.length; ++i) {
colors[vertices[i]] = WHITE
}
// For all vertices, do DFS traversal
for (var i=0; i<vertices.length; ++i) {
var vertex = vertices[i]
if (colors[vertex] == WHITE) {
var result = this._hasLoopDFS(vertices, edges, colors, path, vertex)
if (result.hasLoop) {
return result
}
}
}
return { hasLoop: false }
},
_hasLoopDFS: function(vertices, edges, colors, path, vertex) {
colors[vertex] = GRAY
path.push(vertex)
var adjacentEdges = []
for (var i=0; i<edges.length; ++i) {
var edge = edges[i]
if (edge[0] == vertex) {
adjacentEdges.push(edge)
}
}
for (var i=0; i<adjacentEdges.length; ++i) {
var edge = adjacentEdges[i]
var adjVertex = edge[1]
if (colors[adjVertex] == GRAY) {
var loop = path.slice(path.indexOf(adjVertex))
return { hasLoop: true, loop: loop }
}
if (colors[adjVertex] == WHITE) {
var result = this._hasLoopDFS(vertices, edges, colors, path, adjVertex)
if (result.hasLoop) {
return result
}
}
}
colors[vertex] = BLACK
path.pop(vertex)
return { hasLoop: false }
}
}
window.GraphAlgorithm = GraphAlgorithm
})()