首页 > 其他 > 详细

图论题笔记(一):方格填数

时间:2020-02-27 14:37:20      阅读:101      评论:0      收藏:0      [点我收藏+]

题目:方格填数

技术分享图片

填入0~9的数字。要求:连续的两个数字不能相邻。

(左右、上下、对角都算相邻)

一共有多少种可能的填数方案?

 

这道题有点难,还需要再好好补下递归基础和深度搜索,有时间再整理下注释,Python解法如下

graph_nbr={}
graph_num={}

for row in range(3):
    for col in range(4):
        graph_nbr[(row,col)]=[]        
        graph_num[(row,col)]=None
del graph_nbr[(0,0)]
del graph_nbr[(2,3)]
del graph_num[(0,0)]
del graph_num[(2,3)]

connect=[(-1,0),(-1,-1),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]

def plus_tp(tp1,tp2):
    return (tp1[0]+tp2[0],tp1[1]+tp2[1])

for x in graph_nbr.keys():
    for ct in connect:
        result_plus=plus_tp(x,ct)
        if result_plus in graph_nbr and result_plus not in graph_nbr[x]:
            graph_nbr[x].append(result_plus)

def dfs(graph_key,n,path,limit=10):
    if n==limit:
        global count
        print(count,graph_num)
        count+=1
    
    if n<limit:
        for j in graph_key:
            if j not in path :
                has_i_prev=False
                for nbr in graph_nbr[j]:
                    if graph_num[nbr]==n-1:
                        has_i_prev=True
                        break
                if not has_i_prev:
                    graph_num[j]=n
                    path.append(j)
                    dfs(graph_key,n+1,path)
                    path.pop()
                    graph_num[j]=None

mark=[]
count=1
dfs(graph_key=graph_num.keys(),n=0,path=mark)

 

图论题笔记(一):方格填数

原文:https://www.cnblogs.com/shitianfang/p/12371777.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!