二分图

问题描述

下面是一个 BFS 算法来确定一个图是否是二部图:

function isGraphBipartite(node,graph,visited,distance) {
    const queue = [node];
    distance[node] = 0; //Initial node's distance to itself is 0

    while (queue.length > 0) {
        
        let curNode = queue.shift();
        visited[curNode] = true; 
        
        for (let neighbor of graph[curNode]) {

            
            if(!visited[neighbor]) {
                visited[neighbor] = true;
                distance[neighbor] = distance[curNode] + 1;
                queue.push(neighbor);
            } else {
                if (distance[neighbor] === distance[curNode]) return false; //KEY LINE
            }
        }
    }
    return true;
}

var isBipartite = function(graph) {
    let visited = {};
    let distance = {};

    for (let vertex = 0; vertex < graph.length; vertex++) { 
        if(!visited[vertex]) { 
            if (!isGraphBipartite(vertex,distance)) return false;
        }
    }
    return true;
};

我知道有效的双图不能有奇数周期。我也知道图中相同级别的交叉边的存在会使它作为双图无效。

是否存在某种数学直觉/解释/基本原理,其中如果 (distance[neighbor] === distance[curNode]),则意味着存在相同级别的交叉边以某种方式生成奇数循环?

解决方法

如果节点 A 和 B 到根的路径长度相同,那么它们到这些路径发散的节点的距离相同。如果 A 和 B 也是邻居,则它们与长度为 2*distance+1 的顶点形成一个环,这是奇数。

因此,与根距离相同的节点之间的任何边都表明该图不是二部图。此外,由于相邻节点到根的距离最多相差 1,只有那些边表示奇数循环。当这些边不存在时,所有边将偶数 BFS 级别的节点连接到奇数 BFS 级别的节点,这就是二部分区。