N皇后问题(python实现)
2016-05-26 11:21
525 查看
N皇后问题
n皇后问题是将n个皇后放置在n*n的棋盘上,皇后彼此之间不能相互攻击。给定一个整数n,返回所有不同的n皇后问题的解决方案。
每个解决方案包含一个明确的n皇后放置布局,其中“Q”和“.”分别表示一个女王和一个空位置。
样例
对于4皇后问题存在两种解决的方案:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
思路
由于每行只能有一个皇后,第一行 有N种可能,从一行一列开始 如果一行一列可以放置皇后 则找到下一行第一个能放置皇后的列。如果下一行 没有符合条件的列,就返回上一行找到下一个可以放置皇后的列。遍历的行数 == N 则获得一次 结果。如果在第一行也找不到能放置皇后的列 则查找结束。实现
循环实现class Solution: """ Get all distinct N-Queen solutions @param n: The number of queens @return: All distinct solutions """ def solveNQueens(self, n): # write your code here #每一行和每一列只能有一个皇后 而且必定有一个皇后 n = int(n) result = [] col = [-1]*n k = 0 #row while k>=0: #查看下一列 col[k] = col[k]+1 while col[k]<n and not self.judgePlace(k,col): #col col[k] += 1 if col[k]<n: #获得一次解 if k == n-1: empty = ['.'*n for i in range(0,n)] for i in range(0,n): temp = list(empty[i]) temp[col[i]] = 'Q' empty[i] = ''.join(temp) result.append(empty) #判断下一行 else: k +=1 #清除残留数据 col[k] = -1 #没有找到结果回溯 else: k -= 1 return result def judgePlace(self,k,col): for i in range(0,k): if col[i] == col[k] or (abs(col[k]-col[i]) == abs(k - i)): return False return True
递归实现
class Solution: """ Get all distinct N-Queen solutions @param n: The number of queens @return: All distinct solutions """ def solveNQueens(self, n): n = int(n) result = [] record = [0]*(n+1) self.findResult(result,n,1,1,record) return result def findResult(self,result,total,row,col,record): if row == 0: return result record[row] = col while record[row]<=total and not self.judgePlace(row,record): record[row] += 1 #回溯 if record[row]>total: row -= 1 newCol = record[row] + 1 self.findResult(result,total,row,newCol,record) else: if row == total: empty = ['.'*total for i in range(0,total)] for i in range(0,total): temp = list(empty[i]) temp[record[i+1]-1] = 'Q' empty[i] = ''.join(temp) result.append(empty) #回溯 row -= 1 newCol = record[row] + 1 self.findResult(result,total,row,newCol,record) else: row += 1 self.findResult(result,total,row,1,record) def judgePlace(self,row,col): for i in range(1,row): if col[i] == col[row] or (abs(col[row]-col[i]) == abs(row - i)): return False return True
相关文章推荐
- DTrace patch for Python 2.7.x and 3.x
- Python 对testlink操作
- python 2016 大会 pyconsk ppt ---python dtrace
- python 安装 easy_install 和 pip
- python key and network mointor
- 指定ubuntu下的Python的运行版本
- Python Data Structures - C2 Sort
- Emacs之Python编程环境配置 - elpy
- Python-urllib的API
- Python学习笔记之字符串
- selenium设置元素发现超时等待时间-python
- python元组简介
- Numpy之文件存取
- 使用Python Decorator实现数据驱动测试
- Python Error: “ImportError: No module named six”,用自动安装解决依赖问题
- Python——可执行的伪代码
- python中包含UTF-8编码中文的列表或字典的输出
- Python之美[从菜鸟到高手]--Python垃圾回收机制及gc模块详解
- [python]新手写爬虫v2.5(使用代理的异步爬虫)
- Windows下python2.7.8安装图文教程