二分图
二分图又称作二部图,是图论中的一种特殊模型。 设G=(V,E)是一个无向图,如果顶点V可分割为两个互不相交的子集(A,B),并且图中的每条边(i,j)所关联的两个顶点i和j分别属于这两个不同的顶点集(i in A,j in B),则称图G为一个二分图。图A和图C属于二分区,图B不属于二分图。
二分图检测
染色法
如上图,对图中顶点染色,从其中一个顶点开始染为红色,相邻顶点染为黑色,依次遍历,将整个图中顶点染上红黑颜色。若是出现冲突。视为二分图检测失败。上图B就出现冲突,1-3,1-2,2-3边出现冲突。所以图B不是二分图。
scala实现
import util.control.Breaks.{break, _}
class BiPartitionDetection {
private var G: Graph = _
private var visited: Array[Boolean] = _
private var colors: Array[Int] = _
private var beBiPartite = true
def this(g: Graph) {
this()
G = g
visited = Array.ofDim[Boolean](g.getV())
colors = Array.ofDim[Int](g.getV())
for (i <- 0 until g.getV()) {
colors(i) = -1
}
breakable(
for (j <- 0 until g.getV()) {
if (!visited(j)) {
if (!dfs(j, 0)) {
beBiPartite = false
break()
}
}
}
)
}
private def dfs(v: Int, color: Int): Boolean = {
var result = true
visited(v) = true
colors(v) = color
for (w <- G.getAdjacentSide(v)) {
if (!visited(w)) {
if (!dfs(w, 1 - color)) {
result = false
result
}
} else if (colors(w) == colors(v)) {
result = false
result
}
}
result
}
def isBiPartite(): Boolean = {
beBiPartite
}
}
object BiPartitionDetection {
def apply(g: Graph): BiPartitionDetection = new BiPartitionDetection(g)
def main(args: Array[String]): Unit = {
val g1 = Graph("./data/graph/g.txt")
val bi1 = BiPartitionDetection(g1)
println(bi1.isBiPartite())
val g2 = Graph("./data/graph/g2.txt")
val bi2 = BiPartitionDetection(g2)
println(bi2.isBiPartite())
val g3 = Graph("./data/graph/g3.txt")
val bi3 = BiPartitionDetection(g3)
println(bi3.isBiPartite())
}
}
//true
//false
//true
g.txt
7 6
0 1
0 2
1 3
1 4
2 3
2 6
g2.txt
4 6
0 1
0 2
0 3
1 2
1 3
2 3
g3.txt
4 4
0 1
0 3
1 2
2 3