Python算法之棋盘覆盖

Python算法之棋盘覆盖

问题:在一个NxN个方格组成的棋盘上,有一个方格与其他方格不同,称之为特殊方格,称这样的棋盘为一个特殊棋盘。要求对棋盘上除特殊方格外的所有部分用四种不同方向的L形方块填满。

代码:

def chess(tr, tc, pr, pc, size):
    global mark
    global table
    mark += 1
    count = mark
    if size == 1:
        return
    half = size // 2
    if pr < tr + half and pc < tc + half:
        chess(tr, tc, pr, pc, half)
    else:
        table[tr + half - 1][tc + half - 1] = count
        chess(tr, tc, tr + half - 1, tc + half - 1, half)
    if pr < tr + half and pc >= tc + half:
        chess(tr, tc + half, pr, pc, half)
    else:
        table[tr + half - 1][tc + half] = count
        chess(tr, tc + half, tr + half - 1, tc + half, half)
    if pr>=tr+half and pc=tr+half and pc>=tc+half:
        chess(tr+half,tc+half,pr,pc,half)
    else:
        table[tr+half][tc+half]=count
        chess(tr+half,tc+half,tr+half,tc+half,half)
def show(table):
    n=len(table)
    for i in range(n):
        for j in range(n):
            print(table[i][j],end=' ')
        print(' ')
mark=0
n=8
table=[[-1 for x in range(n)] for y in range(n) ]
chess(0,0,2,2,n)
show(table)

运行结果:

3 3 8 8 24 24 29 29  
3 2 2 8 24 23 23 29  
13 2 -1 18 34 34 23 39  
13 13 18 18 1 34 39 39  
45 45 50 1 1 66 71 71  
45 44 50 50 66 66 65 71  
55 44 44 60 76 65 65 81  
55 55 60 60 76 76 81 81  
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章