[Leetcode][Python]52: N-Queens II

來源:互聯網
上載者: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, return the total number of distinct solutions.

===Comments by Dabay===
不知道和N Queen相比有沒有簡單很多的方法。我這裡的解法思路和N Queen一樣的。

一個一個放皇后,知道能放下最後一個皇后,解法+1。
放第k個皇后的時候,在第k行中找位置,先看列被佔用沒有,然後往左上和右上看斜線被佔用沒有。
‘‘‘

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.