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

yipeiwu_com6年前Python基础

本文实例讲述了Python3解决棋盘覆盖问题的方法。分享给大家供大家参考,具体如下:

问题描述:

在2^k*2^k个方格组成的棋盘中,有一个方格被占用,用下图的4种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<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)位置,如下图所示:

采用分治法每次把棋盘分成4份,如果特殊格子在这个小棋盘中则继续分成4份,如果不在这个小棋盘中就把该小棋盘中靠近中央的那个格子置位,表示L型骨牌的1/3占据此处,每一次递归都会遍历查询4个小棋盘,三个不含有特殊格子的棋盘置位的3个格子正好在大棋盘中央构成一个完整的L型骨牌,依次类推,找到全部覆盖方法。运行结果如下:

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

解决安装tensorflow遇到无法卸载numpy 1.8.0rc1的问题

最近在关注 Deep Learning,就在自己的mac上安装google的开源框架Tensorflow 用 sudo pip install -U tensorflow 安装的时候总...

Python利用itchat对微信中好友数据实现简单分析的方法

Python利用itchat对微信中好友数据实现简单分析的方法

前言 最近在一个微信公众号上看到一个调用微信 API 可以对微信好友进行简单数据分析的一个包 itchat 感觉挺好用的,就简单尝试了一下。 库文档说明链接在这: itchat 安装 在...

python多线程共享变量的使用和效率方法

python多线程可以使任务得到并发执行,但是有时候在执行多次任务的时候,变量出现“意外”。 import threading,time n=0 start=time.time()...

Django Web开发中django-debug-toolbar的配置以及使用

Django Web开发中django-debug-toolbar的配置以及使用

前言 django,web开发中,用django-debug-toolbar来调试请求的接口,无疑是完美至极。 可能本人,见识博浅,才说完美至极, 大神,表喷,抱拳了。 django_d...

python之PyMongo使用总结

 PyMongo是什么 PyMongo是驱动程序,使python程序能够使用Mongodb数据库,使用python编写而成. 安装 环境:Ubuntu 14.04+pyt...