[LeetCode]题解(python):051-N-Queens


题目来源

https://leetcode.com/problems/n-queens/

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.


题意分析
Input: n:integer

Output:a list contains the result

Conditions:典型的n皇后问题(同一列,同一行,同斜线会互相攻击)


题目思路


本题很明显用回溯的方法,经大神指点,这里采用一维数组的方式,如n=4时,list = [2,4,1,3]表示i行第list[i]位置放置皇后,这样就保证了每一行只有一位皇后,然后代码中有个check条件,就是用来判断是不是同一列和斜线的,

注意如果list[i] == list[j]则表示同一列,abs(i - j) == abs(list[i] - list[j])表示同斜线(很明显同一斜线时两点的横纵坐标差相等)

之后,回溯就好了


AC代码(Python)


 1 __author__ = 'YE'
 2 
 3 class Solution(object):
 4     def solveNQueens(self, n):
 5         """
 6         :type n: int
 7         :rtype: List[List[str]]
 8         """
 9         def check(k, j):
10             for i in range(k):
11                 if board[i] == j or abs(k - i) == abs(board[i] - j):
12                     return False
13             return True
14 
15         def dfs(depth, valueList):
16             if depth == n:
17                 res.append(valueList)
18             else:
19                 for i in range(n):
20                     if check(depth, i):
21                         board[depth] = i
22                         s = '.' * n
23                         dfs(depth + 1, valueList + [s[:i] + "Q" + s[i+1:]])
24         res = []
25 
26         board = [-1 for i in range(n)]
27         dfs(0, [])
28 
29         return res
30 
31 s = Solution()
32 n = 4
33 print(s.solveNQueens(n))

 

posted @ 2015-12-28 13:03  loadofleaf  Views(240)  Comments(0Edit  收藏  举报