学习python3第一天,用八皇后练练手。
2018-02-06 14:41
387 查看
#!/usr/bin/python3
# -*- coding:gbk -*-
class EightQueens:
vn_sum = 0
#检查皇后的位置是否符合要求
def check_queens( self, pos ):
for i in range(0, len(pos) - 1 ):
for j in range( i + 1, len(pos) ):
if( abs( i - j ) == abs( pos[i] - pos[j] ) ):
return False
return True
#递归调用,生成8个皇后的位置。
def queens( self, num, pos ):
if( num == 8 ):
self.show(pos)
else:
for i in range(1,9):
if( i not in pos ):
pos.append(i)
if( self.check_queens( pos ) ):
self.queens( num + 1, pos )
pos.pop()
#显示结果
def show( self, pos):
self.vn_sum = self.vn_sum + 1
for i in range( 0, 8 ):
print( ". " * ( pos[i] - 1 ) + "X " + ". " * ( 8 - pos[ i ] + 1 ) )
print( " " )
pos = []
eq = EightQueens()
eq.queens( 0, pos )
print( '共 {} 种走法'.format( eq.vn_sum ) )
# -*- coding:gbk -*-
class EightQueens:
vn_sum = 0
#检查皇后的位置是否符合要求
def check_queens( self, pos ):
for i in range(0, len(pos) - 1 ):
for j in range( i + 1, len(pos) ):
if( abs( i - j ) == abs( pos[i] - pos[j] ) ):
return False
return True
#递归调用,生成8个皇后的位置。
def queens( self, num, pos ):
if( num == 8 ):
self.show(pos)
else:
for i in range(1,9):
if( i not in pos ):
pos.append(i)
if( self.check_queens( pos ) ):
self.queens( num + 1, pos )
pos.pop()
#显示结果
def show( self, pos):
self.vn_sum = self.vn_sum + 1
for i in range( 0, 8 ):
print( ". " * ( pos[i] - 1 ) + "X " + ". " * ( 8 - pos[ i ] + 1 ) )
print( " " )
pos = []
eq = EightQueens()
eq.queens( 0, pos )
print( '共 {} 种走法'.format( eq.vn_sum ) )
相关文章推荐
- python学习第一天 搭建GUI开发环境
- Python学习路径及练手项目合集
- python学习第一天
- Python学习第一天
- 《python tutorial》--python 学习第一天
- 【python】图解算法学习第一天-01-(二分法的一个例子)
- Python学习第一天,第一次接触
- Python学习的第一天
- Python学习第一天
- Python学习二(生成器和八皇后算法)
- python学习入门第一天总结
- Python学习心得(第一天)
- Python 学习第一天
- 第一天学习python执行python文件需要给文件权限
- Python学习第一天心得体会!!!
- 《python tutorial》--python 学习第一天
- 17. Python脚本学习笔记十七Python的八皇后问题
- 人生苦短,我用Python 学习笔记——第一天
- python学习心得-第一天-作业
- python学习之路-第一天-接触python