(graph, startVertex)
| 39 | }; |
| 40 | |
| 41 | const bfsShortestPath = (graph, startVertex) => { |
| 42 | const vertices = graph.vertices; |
| 43 | const adjList = graph.adjList; |
| 44 | const color = {}; |
| 45 | const dist = {}; |
| 46 | const pred = {}; |
| 47 | const queue = [startVertex]; |
| 48 | |
| 49 | vertices.forEach(vertex => { |
| 50 | color[vertex] = Colors.WHITE; |
| 51 | dist[vertex] = 0; |
| 52 | pred[vertex] = null; |
| 53 | }); |
| 54 | |
| 55 | while (queue.length) { |
| 56 | const visiting = queue.shift(); |
| 57 | const neighbors = adjList.get(visiting); |
| 58 | color[visiting] = Colors.GREY; |
| 59 | for (let i = 0; i < neighbors.length; i++) { |
| 60 | const neighbor = neighbors[i]; |
| 61 | if (color[neighbor] === Colors.WHITE) { |
| 62 | color[neighbor] = Colors.GREY; |
| 63 | dist[neighbor] = dist[visiting] + 1; |
| 64 | pred[neighbor] = visiting; |
| 65 | queue.push(neighbor); |
| 66 | } |
| 67 | } |
| 68 | color[visiting] = Colors.BLACK; |
| 69 | } |
| 70 | |
| 71 | return { |
| 72 | distances: dist, |
| 73 | predecessors: pred |
| 74 | }; |
| 75 | }; |
| 76 | |
| 77 | module.exports = { breadthFirstSearch , bfsShortestPath }; |
no test coverage detected