Debian Codegraph @

bipart.go

raw symbols SCIP
1 package graph
2
3 // Bipartition returns a subset U of g's vertices with the property
4 // that every edge of g connects a vertex in U to one outside of U.
5 // If g isn't bipartite, it returns an empty slice and sets ok to false.
6 func Bipartition(g Iterator) (part []int, ok bool) {
7 type color byte
8 const (
9 none color = iota
10 white
11 black
12 )
13 colors := make([]color, g.Order())
14 whiteCount := 0
15 for v := range colors {
16 if colors[v] != none {
17 continue
18 }
19 colors[v] = white
20 whiteCount++
21 for queue := []int{v}; len(queue) > 0; {
22 v := queue[0]
23 queue = queue[1:]
24 if g.Visit(v, func(w int, _ int64) (skip bool) {
25 switch {
26 case colors[w] != none:
27 if colors[v] == colors[w] {
28 skip = true
29 }
30 return
31 case colors[v] == white:
32 colors[w] = black
33 default:
34 colors[w] = white
35 whiteCount++
36 }
37 queue = append(queue, w)
38 return
39 }) {
40 return []int{}, false
41 }
42 }
43 }
44 part = make([]int, 0, whiteCount)
45 for v, color := range colors {
46 if color == white {
47 part = append(part, v)
48 }
49 }
50 return part, true
51 }