1 package main 2 3 import ( 4 "fmt" 5 ) 6 7 type Graphic struct { 8 edges [][]int 9 colors int 10 color []int 11 flag int 12 } 13 14 func (g *Graphic) check(n int) int { 15 nodes := len(g.edges[0]) 16 for i := 0; i < nodes; i++ { 17 if g.color[i] == g.color[n] && i != n && g.edges[i][n] > 0 { 18 return 0 19 } 20 } 21 return 1 22 } 23 24 //递归回溯求解 25 func (g *Graphic) Recuirse(k int) int { 26 nodes := len(g.edges[0]) 27 if k == nodes { //递归经过最后一个顶点,说明找到了一条着色搜索路径, 返回true 28 return 1 29 } else { 30 for c := 1; c <= g.colors; c++ { //对第k个顶点遍历颜色数着色 31 g.color[k] = c 32 if g.check(k) > 0{ //若当前颜色合法, 递归寻找第k+1顶点的着色方案 33 if g.Recuirse(k + 1) > 0{ //如果第i+1及以后的所有顶点着色成功, 反馈给第k-1的递归结果 34 return 1 35 } 36 } 37 } 38 return 0 39 } 40 } 41 42 //迭代回溯求解 43 func (g *Graphic) Iterate() int { 44 i := 0 45 nodes := len(g.edges[0]) 46 for i >= 0 { //着色失败, 表明第0个顶点遍历paint了所有颜色数, 都失败, 返回消息给虚顶点“-1" 47 for g.color[i] <= g.colors { //g.color[i],这里i是变化的, 可以表示下一个顶点, 也可以在下一个顶点着色失败时重新定位到前一个顶点, 重新着色 48 g.color[i]++ 49 if g.check(i) > 0 && i < nodes { //如果该顶点着色合法, i++进入到下一个顶点的着色过程 50 i++ 51 } 52 if i == nodes { //最后一个顶点也着色成功, 跳出双循环, 返回true 53 return 1 54 } 55 } 56 //第i个顶点遍历着色了所有颜色数, 都失败(g.color[i] > g.colors),使i--, 对i--的八个顶点进行下一颜色的着色过程 57 g.color[i] = 0 58 i-- 59 } 60 return 0 61 } 62 63 //打印两种实现方法的着色结果 64 func (g *Graphic) Paint(c int) { 65 nodes := len(g.edges[0]) 66 g.colors = c 67 g.color = make([]int, nodes) 68 fmt.Println("recuirse paint:") 69 if g.Recuirse(0) > 0 { 70 for i := 0; i < nodes; i++ { 71 fmt.Print(g.color[i], " ") 72 } 73 } else { 74 fmt.Println("so solution to paint") 75 } 76 g.color = make([]int, nodes) 77 fmt.Println(" iterate paint:") 78 if g.Iterate() > 0 { 79 for i := 0; i < nodes; i++ { 80 fmt.Print(g.color[i], " ") 81 } 82 } else { 83 fmt.Println("so solution to paint") 84 } 85 86 } 87 88 89 func main() { 90 g := &Graphic{edges: [][]int{{1, 1, 1, 0, 0}, {1, 1, 0, 1, 1}, {1, 0, 1, 1, 1}, {0, 1, 1, 1, 1}, {0, 1, 1, 1, 1}}} 91 g.Paint(3) 92 }