Skip to content

Commit

Permalink
[DFS] Add solutions to NQueens and NQueens II
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Nov 30, 2016
1 parent 5715576 commit 7fc189b
Show file tree
Hide file tree
Showing 2 changed files with 136 additions and 0 deletions.
81 changes: 81 additions & 0 deletions DFS/NQueens.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
* Question Link: https://leetcode.com/problems/n-queens/
* Primary idea: Classic Depth-first Search, fill out row by row, and check column and
* diagnol for each time
*
* Time Complexity: O(n^4), Space Complexity: O(n^2)
*
*/

class NQueens {
func solveNQueens(_ n: Int) -> [[String]] {
guard n > 0 else {
return [[String]]()
}

var boards = [[String]]()
var board = Array(repeating: "", count: n)

dfs(&boards, &board, n, 0)

return boards
}

private func dfs(_ boards: inout [[String]], _ board: inout [String], _ n: Int, _ row: Int) {
if row == n {
boards.append(Array(board))
return
}


for col in 0 ..< n {
if isValid(board, col, row) {
board[row] = setRow(col, n)
dfs(&boards, &board, n, row + 1)
}
}
}

private func isValid(_ board: [String], _ col: Int, _ row: Int) -> Bool {
var c = -1

for i in 0 ..< row {
for j in 0 ..< board[0].characters.count {
if charAt(board[i], j) == "Q" {
c = j
break
}
}

// check col
if c == col {
return false
}

// check diagnol
if abs(c - col) == abs(i - row) {
return false
}
}

return true
}

private func charAt(_ str: String, _ index: Int) -> Character {
return str[str.index(str.startIndex, offsetBy: index)]
}

private func setRow(_ col: Int, _ n: Int) -> String {
var row = ""

for i in 0 ..< n {
if i == col {
row.append("Q")
} else {
row.append(".")
}
}

return row
}
}
55 changes: 55 additions & 0 deletions DFS/NQueensII.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* Question Link: https://leetcode.com/problems/n-queens/
* Primary idea: Classic Depth-first Search, fill out row by row, and check column and
* diagnol for each time, only need to care which column is used
*
* Time Complexity: O(n^3), Space Complexity: O(n^2)
*
*/

class NQueensII {
func totalNQueens(_ n: Int) -> Int {
guard n > 0 else {
return 0
}
var count = 0
var usedCols = Array(repeating: 0, count: n)

dfs(&usedCols, &count, n, 0)

return count
}

private func dfs(_ usedCols: inout [Int], _ count: inout Int, _ n: Int, _ row: Int) {
if row == n {
count += 1
return
}

for col in 0 ..< n {
if isValid(usedCols, row, col) {
usedCols[row] = col
dfs(&usedCols, &count, n, row + 1)
}
}
}

private func isValid(_ usedCols: [Int], _ row: Int, _ col: Int) -> Bool {
var c = -1

for i in 0 ..< row {
c = usedCols[i]

// check col
if c == col {
return false
}

if abs(c - col) == abs(i - row) {
return false
}
}

return true
}
}

0 comments on commit 7fc189b

Please sign in to comment.