|
| 1 | +(function() { |
| 2 | + var WHITE = 0 |
| 3 | + var GRAY = 1 |
| 4 | + var BLACK = 2 |
| 5 | + |
| 6 | + var GraphAlgorithm = { |
| 7 | + // |
| 8 | + // Detect loop in a directed graph, use graph coloring algorithm. |
| 9 | + // |
| 10 | + // @param vertices - array of vertices, a vertex is either an integer or a |
| 11 | + // string |
| 12 | + // @param edges - array of edges, an edge is an array of length 2 which |
| 13 | + // marks the source and destination vertice. |
| 14 | + // i.e., [source, dest] |
| 15 | + // |
| 16 | + // @return { hasLoop: true, loop: [...] } |
| 17 | + // |
| 18 | + hasLoop: function(vertices, edges) { |
| 19 | + var colors = {} |
| 20 | + var path = [] |
| 21 | + |
| 22 | + // Initialize colors to white |
| 23 | + for (var i=0; i<vertices.length; ++i) { |
| 24 | + colors[vertices[i]] = WHITE |
| 25 | + } |
| 26 | + |
| 27 | + // For all vertices, do DFS traversal |
| 28 | + for (var i=0; i<vertices.length; ++i) { |
| 29 | + var vertex = vertices[i] |
| 30 | + if (colors[vertex] == WHITE) { |
| 31 | + var result = this._hasLoopDFS(vertices, edges, colors, path, vertex) |
| 32 | + |
| 33 | + if (result.hasLoop) { |
| 34 | + return result |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return { hasLoop: false } |
| 40 | + }, |
| 41 | + |
| 42 | + _hasLoopDFS: function(vertices, edges, colors, path, vertex) { |
| 43 | + colors[vertex] = GRAY |
| 44 | + path.push(vertex) |
| 45 | + |
| 46 | + var adjacentEdges = [] |
| 47 | + for (var i=0; i<edges.length; ++i) { |
| 48 | + var edge = edges[i] |
| 49 | + if (edge[0] == vertex) { |
| 50 | + adjacentEdges.push(edge) |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + for (var i=0; i<adjacentEdges.length; ++i) { |
| 55 | + var edge = adjacentEdges[i] |
| 56 | + var adjVertex = edge[1] |
| 57 | + |
| 58 | + if (colors[adjVertex] == GRAY) { |
| 59 | + var loop = path.slice(path.indexOf(adjVertex)) |
| 60 | + return { hasLoop: true, loop: loop } |
| 61 | + } |
| 62 | + |
| 63 | + if (colors[adjVertex] == WHITE) { |
| 64 | + var result = this._hasLoopDFS(vertices, edges, colors, path, adjVertex) |
| 65 | + if (result.hasLoop) { |
| 66 | + return result |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + colors[vertex] = BLACK |
| 72 | + path.pop(vertex) |
| 73 | + |
| 74 | + return { hasLoop: false } |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + window.GraphAlgorithm = GraphAlgorithm |
| 79 | +})() |
0 commit comments