深度搜索解数独

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

def guess(ku, i, v, b = 1):
    affects = []
    for j in range(b, 81):
        if (i / 9 == j / 9 \
            or i % 9 == j % 9 \
            or (i / 9 / 3 * 3 == j / 9 / 3 * 3 \
                and i % 9 / 3 * 3 == j % 9 / 3 * 3)) \
           and v in ku[j]:
            ku[j].remove(v)
            affects.append(j)
    ku[i].clear()
    ku[i].add(v)
    return affects

def bfs(ku, i):
    clone = ku[i].copy()
    for v in clone:
        affects = guess(ku, i, v, i + 1)
        if all([len(c) == 1 for c in ku]) or all(ku) and i < 81 and bfs(ku, i + 1):
            return True
        else:
            for j in affects:
                ku[j].add(v)
    ku[i] = clone

ku = [set(range(1, 10)) for i in range(81)]
s = '040300000010608000050000007065910872090070003002084601906735018503400029174890365'
for i in range(81):
    v = int(s[i])
    if 1 <= v <= 9:
        guess(ku, i, v)
for i in range(81):
    if len(ku[i]) > 1:
        bfs(ku, i)
        break
print ''.join(str(next(iter(c)) if len(c) == 1 else 0) for c in ku)
# => 249357186317628954658149237465913872891276543732584691926735418583461729174892365