#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
52:n-queens II
https://oj.leetcode.com/problems/n-queens-ii/
Follow up for n-queens problem.
Now, instead outputting board configurations and return the total number of distinct solutions.
===comments by dabay===
Do not know and N queen compared to have a lot of simple method. My solution here is the same as N queen.
One to put Queen, know can put down the last queen, Solution +1.
When you put the K-Queens, find the position in the K-line, first look at the column is occupied no, and then go to the top left and right to see the slash is occupied No.
‘‘‘
Class Solution:
# @return An integer
def totalnqueens (self, N):
def check_up (R, C, board):
For row in Xrange (R):
If board[row][c] = = ' Q ':
Return False
Else
Return True
def check_upleft (R, C, board):
row = R-1
Column = C-1
While Row>=0 and column>=0:
If board[row][column] = = ' Q ':
Return False
row = Row-1
Column = Column-1
Else
Return True
def check_upright (R, C, board):
row = R-1
Column = C + 1
While Row>=0 and Column<len (board):
If board[row][column] = = ' Q ':
Return False
row = Row-1
Column = column + 1
Else
Return True
def DFS (board, Queens, RES):
If Queens = = 0:
Res[0] = Res[0] + 1
Return
R = Len (board)-Queens
For C in Xrange (LEN (board)):
If not check_up (R, c, board) or not Check_upleft (R, c, board) or not Check_upright (R, C, board):
Continue
Else
Board[r][c] = ' Q '
DFS (board, queens-1, RES)
Board[r][c] = '. '
board = [['. '] * N for _ in Xrange (n)]
#print Board
Queens = N
res = [0]
DFS (Board, Queens, RES)
return Res[0]
def main ():
Sol = solution ()
Print Sol.totalnqueens (5)
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]52:n-queens II