链接

一、题目描述

存在一个 无向图 ,图中有 n 个节点。其中每个节点都有一个介于 0n - 1 之间的唯一编号。给你一个二维数组 graph ,其中 graph[u] 是一个节点数组,由节点 u 的邻接节点组成。形式上,对于 graph[u] 中的每个 v ,都存在一条位于节点 u 和节点 v 之间的无向边。该无向图同时具有以下属性:

  • 不存在自环(graph[u] 不包含 u)。

  • 不存在平行边(graph[u] 不包含重复值)。

  • 如果 vgraph[u] 内,那么 u 也应该在 graph[v] 内(该图是无向图)

  • 这个图可能不是连通图,也就是说两个节点 uv 之间可能不存在一条连通彼此的路径。

二分图 定义:如果能将一个图的节点集合分割成两个独立的子集 AB ,并使图中的每一条边的两个节点一个来自 A 集合,一个来自 B 集合,就将这个图称为 二分图

如果图是二分图,返回 true ;否则,返回 false

 

示例 1:

输入:graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
输出:false
解释:不能将节点分割成两个独立的子集,以使每条边都连通一个子集中的一个节点与另一个子集中的一个节点。

示例 2:

输入:graph = [[1,3],[0,2],[1,3],[0,2]]
输出:true
解释:可以将节点分成两组: {0, 2} 和 {1, 3} 。

 

提示:

  • graph.length == n

  • 1 <= n <= 100

  • 0 <= graph[u].length < n

  • 0 <= graph[u][i] <= n - 1

  • graph[u] 不会包含 u

  • graph[u] 的所有值 互不相同

  • 如果 graph[u] 包含 v,那么 graph[v] 也会包含 u

二、实现

并查集

// 并查集
type UnionFind struct {
	parent []int
}

func NewUnionFind(size int) *UnionFind {
	uf := &UnionFind{
		parent: make([]int, size),
	}
	for i := range uf.parent {
		uf.parent[i] = i
	}
	return uf
}

func (uf *UnionFind) Find(x int) int {
	if uf.parent[x] != x {
		uf.parent[x] = uf.Find(uf.parent[x])
	}
	return uf.parent[x]
}

func (uf *UnionFind) Union(x, y int) {
	rootx := uf.Find(x)
	rooty := uf.Find(y)
	if rootx == rooty {
		return
	}
	if rootx < rooty {
		uf.parent[rooty] = rootx
	} else {
		uf.parent[rootx] = rooty
	}
}

func (uf *UnionFind) IsConnected(x, y int) bool {
	return uf.Find(x) == uf.Find(y)
}

func isBipartite(graph [][]int) bool {
	n := len(graph)
	// 1.
	uf := NewUnionFind(n)
	for node, othernodes := range graph {
		// 把othernodes联通,检查是否和node联通,联通则不行
		for _, othernode := range othernodes {
			uf.Union(othernodes[0], othernode)
			if uf.IsConnected(node, othernode) {
				return false
			}
		}
	}
	return true
}