全部版块 我的主页
论坛 提问 悬赏 求职 新闻 读书 功能一区 经管百科 爱问频道
716 1
2019-07-19
我在做leetcode 37 时, 不知道自己的码错在哪儿了,已经卡了3天了,求大神指点。万分感谢!!!网上的正确答案我也懂了,但是就是找不到自己哪里出错了,谢谢大家!原题是:

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

  • Each of the digits 1-9 must occur exactly once in each row.
  • Each of the digits 1-9 must occur exactly once in each column.
  • Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

Empty cells are indicated by the character '.'.


A sudoku puzzle...


...and its solution numbers marked in red.

Note:

  • The given board contain only digits 1-9 and the character '.'.
  • You may assume that the given Sudoku puzzle will have a single unique solution.
  • The given board size is always 9x9.

我的代码如下:
def checks(board):
    seen = []
    for i, row in enumerate(board):
        for j, c in enumerate(row):
            if c != '.':
                seen += [(c,j),(i,c),(i/3,j/3,c)]
    return len(seen) == len(set(seen))
board=[["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
cboard=[[board[j] for i in range(9)] for j in range(9)]
f=[]
for i in range(9):
    for j in range(9):
        if cboard[j]=='.':
            f+=[[i,j]]


for m in f:
    h=[]
    i,j=m

    cboard[j]='123456789'
    for b in range((i//3)*3,(i//3+1)*3):
        for v in range((j//3)*3,(j//3+1)*3):
            if [b,v] not in f:
                h.append(board[v])
    for b in range(9):
        if [b,j] not in f:
            h.append(board[j])
    for v in range(9):
        if [i,v] not in f:
            h.append(board[v])
    for x in list(set(h)):
        cboard[j]=cboard[j].replace(x,'')
f=[]
for i in range(9):
    for j in range(9):
        if len(cboard[j])>1:
            f+=[[i,j]]        
        l=[]

def final(f):
    if len(f)==0:
        l.append(1)
        return
    if len(f)>0:
        i,j=f[0]
        for x in cboard[j]:
            board[j]=x
            if checks(board):
                print(board)
                print('')
                final(f[1:])

                if len(l) !=0:
                    break
        if not checks(board):
            board[j]='.'
            return                             
    if len(l) !=0:
        return                    

final(f)


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2019-7-19 14:05:46
数独啊 看着就头疼哈哈 努力吧
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

分享

扫码加好友,拉您进群