Chinaunix首页 | 论坛 | 博客
  • 博客访问: 138785
  • 博文数量: 24
  • 博客积分: 1550
  • 博客等级: 上尉
  • 技术积分: 252
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-29 17:25
文章分类

全部博文(24)

文章存档

2018年(1)

2017年(3)

2016年(2)

2014年(2)

2013年(2)

2012年(2)

2011年(2)

2010年(2)

2009年(8)

我的朋友

分类: Python/Ruby

2012-11-11 22:49:56

'''
Created on 2012-8-16

@author: yians
'''
SIZE = 4

grid = [ [0 for col in range(SIZE)] for row in range(SIZE)]

answer = [ [0 for col in range(SIZE)] for row in range(SIZE)]

def placeCol(col):
    end = True
    for row in range(SIZE):
        if grid[row][col] == 0:
            answer[row][col] = 1
            if col == SIZE - 1:
                printAnswer()
                answer[row][col] = 0
                return
            placeRelative(row, col)
            placeCol(col + 1)
            backtrack(row, col)
            answer[row][col] = 0
            end = False
    if end:
        return
            
def placeRelative(row, col):
    for count in range(SIZE):
        grid[row][count] += 1 #加1大大简化了问题
        grid[count][col] += 1        
        #左下
        if row + count < SIZE and col - count >= 0:
            grid[row + count][col - count] += 1
        #左上
        if row - count >= 0 and col - count >= 0:
            grid[row - count][col - count] += 1
        #右上
        if row - count >= 0 and col + count < SIZE:
            grid[row - count][col + count] += 1
        #右下
        if row + count < SIZE and col + count < SIZE:
            grid[row + count][col + count] += 1

def backtrack(row, col):
    for count in range(SIZE):
        grid[row][count] -= 1
        grid[count][col] -= 1
        if row + count < SIZE and col - count >= 0:
            grid[row + count][col - count] -= 1
        if row - count >= 0 and col - count >= 0:
            grid[row - count][col - count] -= 1
        if row - count >= 0 and col + count < SIZE:
            grid[row - count][col + count] -= 1
        if row + count < SIZE and col + count < SIZE:
            grid[row + count][col + count] -= 1
            
def printAnswer():
    for row in range(SIZE):
        print answer[row]
    print "\n"
        
if __name__ == "__main__":    
    placeCol(0)

受网上启发,第二版:
'''
Created on 2012-8-16

@author: yians
'''

SIZE = 92

answer = [0 for col in range(SIZE)]

def placeCol(col):
    if col == SIZE:
        printAnswer()
        return
    for row in range(SIZE):
        answer[col] = row
        if isValid(col):
            placeCol(col + 1)
            
def isValid(col):
    for index in range(0, col):
        if (answer[index] == answer[col]):
            return False
        if (abs(answer[col]-answer[index]) == col - index):
            return False
    return True
            
def printAnswer():
    for col in range(SIZE):
        line = [0 for i in range(SIZE)]
        line[answer[col]]=1
        print line #output transformed answer
    print "\n"
        
if __name__ == "__main__":    
    
    placeCol(0)
阅读(1120) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~