码迷,mamicode.com
首页 > 其他好文 > 详细

051 N Queens

时间:2015-07-07 07:04:44      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

此题即在 052 N Queens 2 基础上稍作改进 并注意返回格式就好

import copy
class Solution:
    def __init__(self):
        self.ans = []
    # @param {integer} n
    # @return {integer}
    def solveNQueens(self, n):
        self.helper(0,[["."]* n for i in range(0,n)],n)
        return self.ans

    def helper(self, level, tmp, n):
        if level == n:
            a = []
            for t in tmp:
                a.append("".join(t))
            self.ans.append(a)
            return
        for pos in range(0,n):
            flag = True
            for i in range(0, level):
                if not flag:
                    break
                if tmp[i][pos] == "Q":
                    flag = False
                    break
                for j in range(0, n):
                    if tmp[i][j]== "Q" and (level-i == pos-j or level-i==j-pos):
                        flag = False
                        break
            if flag:
                tmp[level][pos] = "Q"
                self.helper(level+1, tmp, n)
                tmp[level][pos] = "."

 

051 N Queens

标签:

原文地址:http://www.cnblogs.com/dapanshe/p/4625861.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!