【发布时间】:2021-07-25 21:57:10
【问题描述】:
下面是一个 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;
};
我知道有效的二合图不能有奇数循环。我也知道在图中存在相同水平的交叉边会使它作为二合图无效。
是否存在某种数学直觉/解释/基本原理,如果 (distance[neighbor] === distance[curNode]),这意味着存在相同水平的交叉边缘以某种方式生成奇数循环?
【问题讨论】:
标签: data-structures graph graph-algorithm bipartite