边工作边刷题:70天一遍leetcode: day 29

N-Queen I

错误点:

  • 两个点在对角线上的比较条件:x坐标差和y坐标差相等
  • 在判断当前行和列是否valid的loop里不要做dfs
  • 因为是返回所有有效解,所以dfs为True不立即return,pass around结果list,在内层更新
  • python string和java string一样,immutable,所以不能set单个字符。用list之后join
class Solution(object):
    def solveNQueens(self, n):
        """
        :type n: int
        :rtype: List[List[str]]
        """
        def dfs(cols, rn, n, res, solutions):
            if rn>=n:
                resCp = list()
                for i in range(len(res)):
                    resCp.append(''.join(res[i]))
                solutions.append(resCp)
                return True
                
            for i in range(n):
                valid = True
                for k in range(rn):
                    if cols[k]==i or abs(cols[k]-i)==abs(k-rn):
                        valid = False
                        break
                
                if valid:
                    cols[rn]=i
                    res[rn][i]='Q'
                    dfs(cols, rn+1, n, res, solutions)
                    res[rn][i]='.'

            return False
        
        cols = [-1]*n
        res = [['.']*n for i in range(n)]
        solutions = []
        dfs(cols, 0, n, res, solutions)
        return solutions
        
posted @ 2016-04-19 11:01  absolute100  阅读(84)  评论(0编辑  收藏  举报