Skip to content

Commit

Permalink
N Queens golang
Browse files Browse the repository at this point in the history
  • Loading branch information
GokhanCagritekin committed Aug 2, 2022
1 parent 1f7b2f3 commit fdd67d4
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions go/51-N-Queens.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package main

func solveNQueens(n int) [][]string {
ans, curr := make([][]string, 0), make([]string, 0)
column, diag1, diag2 := make(map[int]int), make(map[int]int), make(map[int]int)
var backtrack func(y int)
backtrack = func(y int) {
if y == n {
ans = append(ans, append([]string{}, curr...))
}
for x := 0; x < n; x++ {
if column[x] > 0 || diag1[x+y] > 0 || diag2[n+x-y-1] > 0 {
continue
}
column[x], diag1[x+y], diag2[n+x-y-1] = 1, 1, 1
s := ""
for i := 0; i < n; i++ {
if i == x {
s += "Q"
} else {
s += "."
}
}
curr = append(curr, s)
backtrack(y + 1)
column[x], diag1[x+y], diag2[n+x-y-1] = 0, 0, 0
curr = curr[:len(curr)-1]
}
}
backtrack(0)
return ans
}

0 comments on commit fdd67d4

Please sign in to comment.