用队列实现广度优先的原理

2021-06-23  本文已影响0人  HelenYin

伪代码

// 构件图
const graph = {};
graph['you'] = ['alice', 'bob', 'claire'];
graph['alice'] = ['peggy'];
graph['claire'] = ['thom', 'jonny'];
graph['peggy'] = [];
graph['thom'] = [];
graph['jonny'] = [];

function BFS () {
    let person = null;
    const queue = [];
    queue.push(...graph['you']);
    while(graph.length > 0) {
        person = graph.shift();
        if (isSeller(person)) {
            console.log(`${person} is seller`);
            return true;
        } else {
            queue.push(...graph[person])
        }
    }
    return false;
}
上一篇 下一篇

猜你喜欢

热点阅读