Skip to content

Commit 9ed5178

Browse files
committed
github.com/masx200/leetcode-test/transform-to-chessboard
1 parent 3ebd6b0 commit 9ed5178

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

transform-to-chessboard/export.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package index
2+
3+
func MovesToChessboard(board [][]int) int {
4+
return movesToChessboard(board)
5+
}
6+
7+
func Itob(b int) bool {
8+
return itob(b)
9+
}
10+
11+
func Min(a, b int) int {
12+
return min(a, b)
13+
}

transform-to-chessboard/go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/masx200/leetcode-test/transform-to-chessboard
2+
3+
go 1.19

transform-to-chessboard/index.go

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package index
2+
3+
func movesToChessboard(board [][]int) int {
4+
var n = len(board)
5+
var rowSum = 0
6+
var colSum = 0
7+
var rowDiff = 0
8+
var colDiff = 0
9+
for i := 0; i < n; i++ {
10+
for j := 0; j < n; j++ {
11+
if itob((board[0][0]) ^ (board[i][0]) ^ (board[0][j]) ^ (board[i][j])) {
12+
return -1
13+
}
14+
}
15+
}
16+
for i := 0; i < n; i++ {
17+
rowSum += board[0][i]
18+
colSum += board[i][0]
19+
rowDiff += Btoi(board[i][0] == i%2)
20+
colDiff += Btoi(board[0][i] == i%2)
21+
}
22+
if n/2 > rowSum || rowSum > (n+1)/2 {
23+
return -1
24+
}
25+
if n/2 > colSum || colSum > (n+1)/2 {
26+
return -1
27+
}
28+
if itob(n % 2) {
29+
if itob(rowDiff % 2) {
30+
rowDiff = n - rowDiff
31+
}
32+
if itob(colDiff % 2) {
33+
colDiff = n - colDiff
34+
}
35+
} else {
36+
rowDiff = min(n-rowDiff, rowDiff)
37+
colDiff = min(n-colDiff, colDiff)
38+
}
39+
return (rowDiff + colDiff) / 2
40+
41+
}
42+
func Btoi(b bool) int {
43+
if b {
44+
return 1
45+
}
46+
return 0
47+
}
48+
func itob(b int) bool {
49+
return b != 0
50+
}
51+
52+
func min(a, b int) int {
53+
if a < b {
54+
return a
55+
}
56+
return b
57+
}

0 commit comments

Comments
 (0)