-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy path167.go
More file actions
153 lines (141 loc) · 2.22 KB
/
167.go
File metadata and controls
153 lines (141 loc) · 2.22 KB
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
// UVa 167 - The Sultan's Successors
package main
import (
"fmt"
"os"
)
var (
max int
visited [][]bool
)
func valid(visited [][]bool) bool {
for i := range visited {
cnt := 0
for j := range visited[i] {
if visited[i][j] {
cnt++
}
}
if cnt > 1 {
return false
}
}
for i := 0; i < len(visited[0]); i++ {
cnt := 0
for j := range visited {
if visited[j][i] {
cnt++
}
}
if cnt > 1 {
return false
}
}
for j := 0; j < 8; j++ {
i := 0
cnt := 0
for d := 0; d < 8; d++ {
x := i + d
y := j - d
if !(x < 0 || x > 7 || y < 0 || y > 7) && visited[x][y] {
cnt++
}
}
if cnt > 1 {
return false
}
}
for i := 1; i < 8; i++ {
j := 7
cnt := 0
for d := 0; d < 8; d++ {
x := i + d
y := j - d
if !(x < 0 || x > 7 || y < 0 || y > 7) && visited[x][y] {
cnt++
}
}
if cnt > 1 {
return false
}
}
for j := 0; j < 8; j++ {
i := 7
cnt := 0
for d := 0; d < 8; d++ {
x := i - d
y := j - d
if !(x < 0 || x > 7 || y < 0 || y > 7) && visited[x][y] {
cnt++
}
}
if cnt > 1 {
return false
}
}
for i := 6; i >= 0; i-- {
j := 7
cnt := 0
for d := 0; d < 8; d++ {
x := i - d
y := j - d
if !(x < 0 || x > 7 || y < 0 || y > 7) && visited[x][y] {
cnt++
}
}
if cnt > 1 {
return false
}
}
return true
}
func sum(board [][]int, visited [][]bool) {
total := 0
for i, v := range visited {
for j, vv := range v {
if vv {
total += board[i][j]
}
}
}
if total > max {
max = total
}
}
func backtracking(board [][]int, row int) {
if !valid(visited) {
return
}
if row == 8 {
sum(board, visited)
return
}
for i := range board[0] {
visited[row][i] = true
backtracking(board, row+1)
visited[row][i] = false
}
}
func main() {
in, _ := os.Open("167.in")
defer in.Close()
out, _ := os.Create("167.out")
defer out.Close()
var k int
for fmt.Fscanf(in, "%d", &k); k > 0; k-- {
board := make([][]int, 8)
for i := range board {
board[i] = make([]int, 8)
for j := range board[i] {
fmt.Fscanf(in, "%d", &board[i][j])
}
}
visited = make([][]bool, 8)
for i := range visited {
visited[i] = make([]bool, 8)
}
max = 0
backtracking(board, 0)
fmt.Fprintln(out, max)
}
}