源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python3解决棋盘覆盖问题的方法示例

  • 时间:2020-01-16 21:48 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python3解决棋盘覆盖问题的方法示例
本文实例讲述了Python3解决棋盘覆盖问题的方法。分享给大家供大家参考,具体如下: [b]问题描述:[/b] 在2^k*2^k个方格组成的棋盘中,有一个方格被占用,用下图的4种L型骨牌覆盖所有棋盘上的其余所有方格,不能重叠。 [img]http://files.jb51.net/file_images/article/201712/2017127114805119.jpg?201711711532[/img] [b]代码如下:[/b]
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<tc+half:
    chess(tr+half,tc,pr,pc,half)
  else:
    table[tr+half][tc+half-1]=count
    chess(tr+half,tc,tr+half,tc+half-1,half)
  if pr>=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)

n是棋盘宽度,必须是2^k,本例中n=8,特殊格子在(2,2)位置,如下图所示: [img]http://files.jb51.net/file_images/article/201712/2017127115324261.jpg?2017117115344[/img] 采用分治法每次把棋盘分成4份,如果特殊格子在这个小棋盘中则继续分成4份,如果不在这个小棋盘中就把该小棋盘中靠近中央的那个格子置位,表示L型骨牌的1/3占据此处,每一次递归都会遍历查询4个小棋盘,三个不含有特殊格子的棋盘置位的3个格子正好在大棋盘中央构成一个完整的L型骨牌,依次类推,找到全部覆盖方法。运行结果如下: [img]http://files.jb51.net/file_images/article/201712/2017127115355505.png?201711712448[/img] 更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/946.htm]Python加密解密算法与技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/788.htm]Python编码操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》及《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》 希望本文所述对大家Python程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部