1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
| const ( black = "Black" white = "White" none = "None" )
type pair struct{ x, y int } var dir8 = []pair{ {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1} }
func gobang(pieces [][]int) string { color := make(map[pair]int, len(pieces)+1) for _, p := range pieces { p[2]++ color[pair{p[0], p[1]}] = p[2] }
checkWin := func(i, j, c int) bool { for k, d := range dir8[:4] { cnt := 1 for x, y := i+d.x, j+d.y; color[pair{x, y}] == c; x, y = x+d.x, y+d.y { cnt++ } d = dir8[k^4] for x, y := i+d.x, j+d.y; color[pair{x, y}] == c; x, y = x+d.x, y+d.y { cnt++ } if cnt >= 5 { return true } } return false }
for _, p := range pieces { if p[2] == 2 { continue } i, j := p[0], p[1] for _, d := range dir8 { if x, y := i+d.x, j+d.y; color[pair{x, y}] == 0 && checkWin(x, y, 1) { return black } } }
whites := map[pair]bool{} posW := pair{} for _, p := range pieces { if p[2] == 1 { continue } i, j := p[0], p[1] for _, d := range dir8 { x, y := i+d.x, j+d.y q := pair{x, y} if color[q] == 0 && checkWin(x, y, 2) { if whites[q] = true; len(whites) > 1 { return white } posW = q } } }
if len(whites) == 1 { color[posW] = 1 blacks := map[pair]bool{} checkBlackWin := func(i, j int) bool { for _, d := range dir8 { x, y := i+d.x, j+d.y p := pair{x, y} if color[p] == 0 && checkWin(x, y, 1) { if blacks[p] = true; len(blacks) > 1 { return true } } } return false } checkBlackWin(posW.x, posW.y) for _, p := range pieces { if p[2] == 1 && checkBlackWin(p[0], p[1]) { return black } } return none }
checkBlackWin := func(i0, j0 int) bool { blacks := map[pair]bool{} for k, d := range dir8 { for l, i, j := 0, i0, j0; l < 5; l++ { i += d.x j += d.y p := pair{i, j} if color[p] > 0 { continue } cnt := 1 for x, y := i+d.x, j+d.y; color[pair{x, y}] == 1; x, y = x+d.x, y+d.y { cnt++ } d2 := dir8[k^4] for x, y := i+d2.x, j+d2.y; color[pair{x, y}] == 1; x, y = x+d2.x, y+d2.y { cnt++ } if cnt >= 5 { if blacks[p] = true; len(blacks) > 1 { return true } } } } return false } vis := map[pair]bool{} for _, p := range pieces { if p[2] == 2 { continue } i, j := p[0], p[1] for dx := -2; dx <= 2; dx++ { for dy := -2; dy <= 2; dy++ { if dx == 0 && dy == 0 { continue } x, y := i+dx, j+dy q := pair{x, y} if vis[q] || color[q] > 0 { continue } color[q] = 1 vis[q] = true if checkBlackWin(x, y) { return black } delete(color, q) } } } return none }
|