def isOK(row,col): '''Is it possible that a queen is put at (row,col)?''' for i in range(1,row): if col==queen[i-1] or col-queen[i-1]==row-i or col-queen[i-1]==i-row: return False return True def DFS(row): if row==n+1: print queen return for i in range(1,n+1): if isOK(row,i): queen.append(i) DFS(row+1) queen.pop() n=int(raw_input('Enter the number of queens: ')) queen=[] DFS(1)
看了一下午的《Python简明教程》,顺手写了个N皇后的程序玩玩儿。程序只用到了基本的功能。贴在这里记录一下。 def isOK(row,col): Is it possible that a queen is put at (row,col)? for i in range(1,row): if col==queen[i-1] or col-quee