[Leetcode] [Python]52:n-queens II

Source: Internet
Author: User

#-*-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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.