数据结构 -- 图中二分图检测

二分图

二分图又称作二部图,是图论中的一种特殊模型。 设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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值