棋盘覆盖问题是比较经典的分治算法试题,用python写了一下,学习python中,顺便复习一下算法
# -*- coding:utf-8 -
#-------------------------------------------------------------------------------
# Name: qipanfugai
# Purpose: test
#
# Author: qyl
#
# Created: 29-11-2011
# Copyright: (c) qyl 2011
# Licence: <all for you>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
def qipanfugai(tr,tc,sr,sc,size):
'''
tr:棋盘左上角行号
tc:棋盘左上角列号
sr:棋盘特殊格行号
sc:棋盘特殊格列号
'''
if size == 1:
return
s = size/2
# 特殊方格在左上角
if sr < s + tr and sc < s + tc:
print u'在行:',s + tr,u',列:',s + tc,u'“方格放','_|'
#print 'on row:',s + tr,',column:',s + tc,',set','"_|"'
# 填充左上角
qipanfugai(tr,tc,sr,sc,s)
# 填充右上角
qipanfugai(tr,tc + s,tr + s - 1,tc + s,s)
# 填充左下角
qipanfugai(tr + s,tc,tr + s,tc + s - 1,s)
# 填充右下角
qipanfugai(tr + s,tc + s,tr + s,tc + s,s)
# 特殊方格在左下角
elif sr >= s + tr and sc < s + tc:
print u'在行:',s + tr -1,u',列:',s + tc,u'“方格放','^|'
#print 'on row:',s + tr - 1,',column:',s + tc,',set','"^|"'
# 填充左上角
qipanfugai(tr,tc,tr + s - 1,tc + s - 1,s)
# 填充右上角
qipanfugai(tr,tc + s,tr + s - 1,tc + s,s)
# 填充左下角
qipanfugai(tr + s,tc,sr,sc,s)
# 填充右下角
qipanfugai(tr + s,tc + s,tr + s,tc + s,s)
# 特殊方格在右上角
elif sr < s + tr and sc >= s + tc:
print u'在行:',s + tr,u',列:',s + tc - 1,u'“方格放','|_'
#print 'on row:',s + tr,',column:',s + tc - 1,',set','"|_"'
# 填充左上角
qipanfugai(tr,tc,tr + s - 1,tc + s - 1,s)
# 填充右上角
qipanfugai(tr,tc + s,sr,sc,s)
# 填充左下角
qipanfugai(tr + s,tc,tr + s,tc + s - 1,s)
# 填充右下角
qipanfugai(tr + s,tc + s,tr + s,tc + s,s)
# 特殊方格在右下角
elif sr >= s + tr and sc >= s + tc:
print u'在行:',s + tr - 1,u',列:',s + tc - 1,u'“方格放','|^'
#print 'on row:',s + tr - 1,',column:',s + tc - 1,',set','"|^"'
# 填充左上角
qipanfugai(tr,tc,tr + s - 1,tc + s - 1,s)
# 填充右上角
qipanfugai(tr,tc + s,tr + s - 1,tc + s,s)
# 填充左下角
qipanfugai(tr + s,tc,tr + s,tc + s - 1,s)
# 填充右下角
qipanfugai(tr + s,tc + s,sr,sc,s)
def main():
qipanfugai(0,0,1,1,16)
if __name__ == '__main__':
main()