算法笔记9:访问所有节点的最短路径

117 阅读1分钟

847.访问所有节点的最短路径

对图相关的解法完全不了解:

  1. 每条边的长度为 1,所以适用 BFS 进行路径搜索。
  2. 路径搜索的过程中,需要存储哪些节点访问过。这块没看题解之前想到确实是求解过程中需要存储的信息,但是没想到可以用位存储。说来惭愧,其实项目里还用到过位存储压缩权限码大小。
  3. 找到答案需要满足的条件是所有节点都访问过就行了。

代码如下:

const shortestPathLength = graph => {
    const len = graph.length;
    const queue = [];
    // 2-dimensional array to store if a node is visited in certain status
    // because there are only 2 types of status for each node
    // so we can use binary numbers to reduce the space
    const visited = Array(len).fill(0).map(() => Array(1 << len).fill(false));
    for(let i = 0; i < len; i++) {
        queue.push([i, 1 << i, 0]);
        visited[i][1 << i] = true;
    }

    while(queue.length) {
        const t = queue.shift();
        const [i, mask, dist] = t;
        if (mask === (1 << len) - 1) {
            return dist;
        }

        for(const v of graph[i]) {
            const nextMask = mask | (1 << v);
            if (!visited[v][nextMask]) {
                visited[v][nextMask] = true;
                queue.push([v, nextMask, dist + 1]);
            }
        }
    }

    return 0;
};