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
| var res [][]string
func solveNQueens(n int) [][]string { res = make([][]string, 0) board := make([][]string, n) for i := range board { board[i] = make([]string, n) for j := range board[i] { board[i][j] = "." } } backtrace(0, board) return res }
func backtrace(row int, board [][]string) { n := len(board) if row == n { b := make([]string, n) sb := &strings.Builder{} for i := 0; i < n; i++ { sb.Reset() for j := 0; j < n; j++ { sb.WriteString(board[i][j]) } b[i] = sb.String() } res = append(res, b) return }
for col := 0; col < n; col++ { if !isValid(row, col, board) { continue } board[row][col] = "Q" backtrace(row + 1, board) board[row][col] = "." } }
func isValid(row, col int, board [][]string) bool { n := len(board)
for i := 0; i < n; i++ { if board[i][col] == "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 } }
for i, j := row - 1, col + 1; i >= 0 && j < n; i, j = i-1, j+1 { if board[i][j] == "Q" { return false } }
return true }
|