4.5 KiB
4.5 KiB
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
587d825c367417b2b2512c90 | Breadth-First Search | 1 | 广度优先搜索 |
Description
Infinity
。这为从起始节点无法访问节点的情况提供了参考。接下来,您将要从开始节点转到其邻居。这些邻居是一个边缘,此时你应该添加一个距离单位到你要跟踪的距离。最后,有助于实现广度优先搜索算法的重要数据结构是队列。这是一个数组,您可以在其中添加元素到一端并从另一端删除元素。这也称为FIFO或先进先出数据结构。 Instructions
bfs()
,它将邻接矩阵图(二维数组)和节点标签根作为参数。节点标签只是0
到n - 1
之间节点的整数值,其中n
是图中节点的总数。您的函数将输出JavaScript对象键值对与节点及其与根的距离。如果无法到达节点,则其距离应为Infinity
。 Tests
tests:
- text: '输入图<code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> ,起始节点为<code>1</code>应该返回<code>{0: 1, 1: 0, 2: 1, 3: 2}</code>'
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 <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>1</code> should return <code>{0: 1, 1: 0, 2: 1, 3: 2}</code>");'
- text: '输入图<code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> ,起始节点为<code>1</code>应该返回<code>{0: 1, 1: 0, 2: 1, 3: Infinity}</code>'
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 <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> with a start node of <code>1</code> should return <code>{0: 1, 1: 0, 2: 1, 3: Infinity}</code>");'
- text: '输入图<code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> ,起始节点为<code>0</code>应该返回<code>{0: 0, 1: 1, 2: 2, 3: 3}</code>'
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 <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>0</code> should return <code>{0: 0, 1: 1, 2: 2, 3: 3}</code>");'
- text: '起始节点为<code>0</code>的输入图<code>[[0, 1], [1, 0]]</code>应返回<code>{0: 0, 1: 1}</code>'
testString: 'assert((function() { var graph = [[0, 1], [1, 0]]; var results = bfs(graph, 0); return isEquivalent(results, {0: 0, 1: 1})})(), "The input graph <code>[[0, 1], [1, 0]]</code> with a start node of <code>0</code> should return <code>{0: 0, 1: 1}</code>");'
Challenge Seed
function bfs(graph, root) {
// Distance object returned
var nodesLen = {};
return nodesLen;
};
var exBFSGraph = [
[0, 1, 0, 0],
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0]
];
console.log(bfs(exBFSGraph, 3));
After Test
console.info('after the test');
Solution
// solution required