MCPcopy Index your code
hub / github.com/loiane/javascript-datastructures-algorithms / bfsShortestPath

Function bfsShortestPath

src/13-graph/bfs.js:41–75  ·  view source on GitHub ↗
(graph, startVertex)

Source from the content-addressed store, hash-verified

39};
40
41const 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
77module.exports = { breadthFirstSearch , bfsShortestPath };

Callers 3

02-using-bfs.tsFile · 0.90
graph.test.tsFile · 0.90
02-using-bfs.jsFile · 0.70

Calls 3

forEachMethod · 0.45
getMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected