Data structures 二部图

Data structures 二部图,data-structures,graph,graph-algorithm,bipartite,Data Structures,Graph,Graph Algorithm,Bipartite,下面是确定图是否为二部图的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()

下面是确定图是否为二部图的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, graph, visited, distance)) return false;
        }
    }
    return true;
};

函数isGraphBipartite(节点、图形、访问、距离){
常量队列=[node];
距离[节点]=0;//初始节点到自身的距离为0
while(queue.length>0){
设curNode=queue.shift();
已访问[curNode]=真;
for(让图[curNode]的邻居){
如果(!访问[邻居]){
拜访[邻居]=真实;
距离[邻居]=距离[节点]+1;
队列推送(邻居);
}否则{
if(distance[neighbor]==distance[curNode])返回false;//键行
}
}
}
返回true;
}
var isBipartite=函数(图){
让我们={};
设距离={};
对于(设顶点=0;顶点
我知道一个有效的双图不能有奇数圈。我还知道,图中存在相同水平的交叉边将使它作为双图失效


是否存在某种数学直觉/解释/基本原理,其中if(距离[邻居]==距离[curNode]),这意味着存在以某种方式生成奇数循环的相同水平交叉边?

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


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

感谢您的详细回复!在这个问题下,我们将进行几次试运行,以充分了解情况。