考虑到python的流行,于是乎我也开始凑热闹的玩起了python。
第一次写,写了一个最简单的递归八皇后~算是基础语法训练
贴代码,欢迎高手为我指出问题,不胜感激
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | # _*_ coding: utf-8 _*_ ''' Created on Aug 22, 2010 @author: yanglingfeng ''' import math a=[[0 for column in range(8)] for row in range(8)] hash1=[0 for x in range(0,8)] hash2=[0 for x in range(0,16)] hash3=[0 for x in range(0,16)] co=0 def dfs(line): global co if line>=8: str="" co=co+1 for i in range(0,8): for j in range(0,8): if a[i][j]==1: str=str+'@' else: str=str+'*' str=str+'\n' print str return else: i=0 for i in range(0,8): if (hash1[i]==1 or hash2[i+line]==1 or hash3[i-line+8]==1): continue else: hash1[i]=1 hash2[i+line]=1 hash3[i-line+8]=1 a[line][i]=1 dfs(line+1) hash1[i]=0 hash2[i+line]=0 hash3[i-line+8]=0 a[line][i]=0 return if __name__ == '__main__': dfs(0) print "共计",co,"种解" |

评论:4
参与评论