785. 判断二分图
参考官方题解的染色法。
paint
函数对idx
的邻接点染色并递归。
对一个点使用paint
函数会将其所在的整个连通图染色。
考虑到题中的图可能不是单连通图,因此需要对每个未染色的点 染色 并调用paint
函数。
package main
import "fmt"
const (
plain=iota
red
black
)
func paint(idx int, graph [][]int, color []int) bool {
for _,v:=range graph[idx]{
if color[v]==plain{
color[v]=3-color[idx]
if !paint(v,graph,color){
return false
}
}else if color[v]==color[idx]{
return false
}
}
return true
}
func isBipartite(graph [][]int) bool {
color:=make([]int, len(graph))
for i:=0;i< len(graph);i++{
if color[i]==plain{
color[i]=red
}
if !paint(i, graph, color){
return false
}
}
return true
}
func main() {
nums:=[][]int{{1,2,3},{0,2},{0,1,3},{0,2}}
fmt.Println(isBipartite(nums))
}