...
https://leetcode.com/problems/n-queens/
Code Block | ||
---|---|---|
| ||
func solveNQueens(n int) (result [][]string) {
solve(&result, n, newBoard(n), 0)
return
}
func solve(result *[][]string, n int, board [][]byte, row int) {
if row == n {
*result = append(*result, flat(board))
return
}
for col := 0; col < n; col++ {
if !isValid(board, row, col) {
continue
}
board[row][col] = 'Q'
solve(result, n, board, row+1)
board[row][col] = '.'
}
}
func isValid(board [][]byte, row, col int) bool {
n := len(board)
for i := 0; i <= row; i++ {
if board[i][col] == 'Q' {
return false
}
}
for i, j := row-1, col+1; i >= 0 && j < n; i, j = i-1, j+1 {
if board[i][j] == 'Q' {
return false
}
}
for i, j := row-1, col-1; i >= 0 && j >= 0; i, j = i-1, j-1 {
if board[i][j] == 'Q' {
return false
}
}
return true
}
func newBoard(n int) [][]byte {
board := make([][]byte, n)
for i := range board {
board[i] = bytes.Repeat([]byte("."), n)
}
return board
}
func flat(board [][]byte) []string {
result := make([]string, len(board))
for i := range result {
result[i] = string(board[i])
}
return result
} |
LC 52. N-Queens II N 皇后 II
https://leetcode.com/problems/n-queens-ii/
Code Block |
---|
func totalNQueens(n int) (result int) {
solve(&result, n, newBoard(n), 0)
return
}
func solve(result *int, n int, board [][]byte, row int) {
if row == n {
(*result)++
return
}
for col := 0; col < n; col++ {
if !isValid(board, row, col) {
continue
}
board[row][col] = 'Q'
solve(result, n, board, row+1)
board[row][col] = '.'
}
}
func isValid(board [][]byte, row, col int) bool {
n := len(board)
for i := 0; i <= row; i++ {
if board[i][col] == 'Q' {
return false
}
}
for i, j := row-1, col+1; i >= 0 && j < n; i, j = i-1, j+1 {
if board[i][j] == 'Q' {
return false
}
}
for i, j := row-1, col-1; i >= 0 && j >= 0; i, j = i-1, j-1 {
if board[i][j] == 'Q' {
return false
}
}
return true
}
func newBoard(n int) [][]byte {
board := make([][]byte, n)
for i := range board {
board[i] = bytes.Repeat([]byte("."), n)
}
return board
}
|