miracles1919 / js-algorithm

js algorithm
1 stars 0 forks source link

【数据结构】图 #11

Open miracles1919 opened 2 years ago

miracles1919 commented 2 years ago

参考:图论基础及遍历算法

图是由节点和边构成的

常用邻接表和领接矩阵来实现

度 (degree)

miracles1919 commented 2 years ago

797. 所有可能的路径

时间复杂度:O(n x 2^n) 空间复杂度:O(n)

var allPathsSourceTarget = function (graph) {
    const res = [];
    const path = [0];
    const n = graph.length;

    function traverse (graph, node) {
        // 到达终点
        if (node === n - 1) {
            res.push(path.slice())
            return
        }

        // 递归相邻节点
        for(const v of graph[node]) {
            path.push(v)
            traverse(graph, v)
            path.pop()
        }
    }

    traverse(graph, 0);
    return res;
};
miracles1919 commented 2 years ago

785. 判断二分图

miracles1919 commented 2 years ago

886. 可能的二分法

var possibleBipartition = function (n, dislikes) {
  function buildGraph (n, dislikes) {
    const graph = new Array(n + 1).fill(0).map(() => []);
    dislikes.forEach((item) => {
      const [x, y] = item;
      graph[x].push(y);
      graph[y].push(x);
    });
    return graph;
  }

  const graph = buildGraph(n, dislikes) 
  return isBipartite(graph)
}