Infinity
. This gives a reference for the case where a node may not be reachable from your start node.
Next, you'll want to go from the start node to its neighbors. These neighbors are one edge away and at this point you should add one unit of distance to the distances you're keeping track of.
Last, an important data structure that will help implement the breadth-first search algorithm is the queue. This is an array where you can add elements to one end and remove elements from the other end. This is also known as a FIFO or First-In-First-Out data structure.
bfs()
that takes an adjacency matrix graph (a two-dimensional array) and a node label root as parameters. The node label will just be the integer value of the node between 0
and n - 1
, where n
is the total number of nodes in the graph.
Your function will output a JavaScript object key-value pairs with the node and its distance from the root. If the node could not be reached, it should have a distance of Infinity
.
[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]
with a start node of 1
should return {0: 1, 1: 0, 2: 1, 3: 2}
'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]; var results = bfs(graph, 1); return isEquivalent(results, {0: 1, 1: 0, 2: 1, 3: 2})})(), ''The input graph [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]
with a start node of 1
should return {0: 1, 1: 0, 2: 1, 3: 2}
'');'
- text: 'The input graph [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]
with a start node of 1
should return {0: 1, 1: 0, 2: 1, 3: Infinity}
'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]; var results = bfs(graph, 1); return isEquivalent(results, {0: 1, 1: 0, 2: 1, 3: Infinity})})(), ''The input graph [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]
with a start node of 1
should return {0: 1, 1: 0, 2: 1, 3: Infinity}
'');'
- text: 'The input graph [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]
with a start node of 0
should return {0: 0, 1: 1, 2: 2, 3: 3}
'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]; var results = bfs(graph, 0); return isEquivalent(results, {0: 0, 1: 1, 2: 2, 3: 3})})(), ''The input graph [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]
with a start node of 0
should return {0: 0, 1: 1, 2: 2, 3: 3}
'');'
- text: 'The input graph [[0, 1], [1, 0]]
with a start node of 0
should return {0: 0, 1: 1}
'
testString: 'assert((function() { var graph = [[0, 1], [1, 0]]; var results = bfs(graph, 0); return isEquivalent(results, {0: 0, 1: 1})})(), ''The input graph [[0, 1], [1, 0]]
with a start node of 0
should return {0: 0, 1: 1}
'');'
```