Skip to content

Instantly share code, notes, and snippets.

@chairco
Last active December 19, 2018 01:41
Show Gist options
  • Save chairco/7b05b63511f16cf9938a88c5fc473e4f to your computer and use it in GitHub Desktop.
Save chairco/7b05b63511f16cf9938a88c5fc473e4f to your computer and use it in GitHub Desktop.
一些想到的寫法

九宮格分群

#

#-*- coding: utf-8 -*-

a = [[1,1,1,1,1,1,1,1,1], [2,2,2,2,2,2,2,2,2], [3,3,3,3,3,3,3,3,3],
     [4,4,4,4,4,4,4,4,4], [5,5,5,5,5,5,5,5,5], [6,6,6,6,6,6,6,6,6],
     [7,7,7,7,7,7,7,7,7], [8,8,8,8,8,8,8,8,8], [9,9,9,9,9,9,9,9,9]]


matrix = [[] for _ in range(len(a))]

count, group = 0, 0 
for i in range(0, 9):
    print(f"i={i%3}, count={count}")
    c = 0
    for j in range(0, 9, 3):
        print(f"  {group+c}: {a[i][j:j+3]}")
        matrix[group+c].extend(a[i][j:j+3])
        c += 1

    count += 1
    if count%3 == 0:
        print('-'*20)
        group = count

print(matrix)

output:

i=0, count=0
  0: [1, 1, 1]
  1: [1, 1, 1]
  2: [1, 1, 1]
i=1, count=1
  0: [2, 2, 2]
  1: [2, 2, 2]
  2: [2, 2, 2]
i=2, count=2
  0: [3, 3, 3]
  1: [3, 3, 3]
  2: [3, 3, 3]
--------------------
i=0, count=3
  3: [4, 4, 4]
  4: [4, 4, 4]
  5: [4, 4, 4]
i=1, count=4
  3: [5, 5, 5]
  4: [5, 5, 5]
  5: [5, 5, 5]
i=2, count=5
  3: [6, 6, 6]
  4: [6, 6, 6]
  5: [6, 6, 6]
--------------------
i=0, count=6
  6: [7, 7, 7]
  7: [7, 7, 7]
  8: [7, 7, 7]
i=1, count=7
  6: [8, 8, 8]
  7: [8, 8, 8]
  8: [8, 8, 8]
i=2, count=8
  6: [9, 9, 9]
  7: [9, 9, 9]
  8: [9, 9, 9]
--------------------
[[1, 1, 1, 2, 2, 2, 3, 3, 3], [1, 1, 1, 2, 2, 2, 3, 3, 3], [1, 1, 1, 2, 2, 2, 3, 3, 3], [4, 4, 4, 5, 5, 5, 6, 6, 6], [4, 4, 4, 5, 5, 5, 6, 6, 6], [4, 4, 4, 5, 5, 5, 6, 6, 6], [7, 7, 7, 8, 8, 8, 9, 9, 9], [7, 7, 7, 8, 8, 8, 9, 9, 9], [7, 7, 7, 8, 8, 8, 9, 9, 9]]
@chairco
Copy link
Author

chairco commented Dec 19, 2018

#-*- coding: utf-8 -*-


def solveSudoku(board):
    """
    :type board: List[List[str]]
    :rtype: void Do not return anything, modify board in-place instead.
    """
    #board = init(board=board)

    while True:
        board = check_row(board=board)
        board = check_col(board=board)
        board = check_group(board=board)

        if check_set(board) == True:
            break

    return board


def init(board):
    sudoku = {str(i) for i in range(1, 10)}

    # row first
    rows = []
    for idx, row in enumerate(board):
        rows.append([cell for cell in row if cell != '.' and not isinstance(cell, set)])

    # check row first
    for idx, b in enumerate(board):
        update = sudoku - set(rows[idx])
        for idy, cell in enumerate(b):
            if cell == '.':
                board[idx][idy] = update

    '''
    # col first
    cols = []
    board_col = [list(b) for b in zip(*board)]
    for idx, col in enumerate(board_col):
        cols.append([cell for cell in col if cell != '.' and not isinstance(cell, set)])


    # check col
    board = [list(b) for b in zip(*board)]
    for idx, b in enumerate(board):
        for idy, cell in enumerate(b):
            if isinstance(cell, set):
                board[idx][idy] = cell - set(cols[idx])#b[idy] - set(cols[idx])

    return [list(b) for b in zip(*board)]
    '''
    return board

def check_row(board):
    sudoku = {str(i) for i in range(1, 10)}
    rows = []
    for idx, row in enumerate(board):
        #rows.append([cell for cell in row if not isinstance(cell, set)])
        rows.append([cell for cell in row if cell != '.' and not isinstance(cell, set)])

    for idx, b in enumerate(board):
        for idy, cell in enumerate(b):
            if cell == '.':
                board[idx][idy] = sudoku - set(rows[idx])
            elif isinstance(cell, set):
                data = cell - set(rows[idx])
                board[idx][idy] = data if len(data) > 1 else ''.join(data)

    return board


def check_col(board):
    cols = []
    board = [list(b) for b in zip(*board)]
    for idx, col in enumerate(board):
        #cols.append([cell for cell in col if not isinstance(cell, set)])
        cols.append([cell for cell in col if cell != '.' and not isinstance(cell, set)])

    for idx, b in enumerate(board):
        for idy, cell in enumerate(b):
            if isinstance(cell, set):
                data = cell - set(cols[idx])
                board[idx][idy] = data if len(data) > 1 else ''.join(data)

    return [list(b) for b in zip(*board)]


def check_group(board):
    # check group, while loop
    board = [list(b) for b in zip(*board)]
    matrix = [[] for _ in range(len(board))]
    count, group = 0, 0
    for i in range(0, 9):
        c = 0
        for j in range(0, 9, 3):
            matrix[group + c].extend(board[i][j:j + 3])
            c += 1

        count += 1
        if count % 3 == 0:
            group = count

    # check
    row = [[] for _ in range(len(board))]
    for idx, m in enumerate(matrix):
        for cell in m:
            if not isinstance(cell, set):
                row[idx].append(cell)

    for idx, m in enumerate(matrix):
        for idy, cell in enumerate(m):
            if isinstance(cell, set):
                data = cell - set(row[idx])
                matrix[idx][idy] = data if len(data) > 1 else ''.join(data)

    board = [[] for _ in range(len(board))]
    count, group = 0, 0
    for i in range(0, 9):
        c = 0
        for j in range(0, 9, 3):
            board[group + c].extend(matrix[i][j:j + 3])
            c += 1

        count += 1
        if count % 3 == 0:
            group = count

    return [list(b) for b in zip(*board)]


def check_set(board):
    for b in board:
        for cell in b:
            if isinstance(cell, set):
                return False
    return True


if __name__ == '__main__':
    b = [["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"]]
    print(solveSudoku(board=b))  
    # [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]

    b = [['4', '.', '.', '1', '8', '.', '.', '5', '7'], ['5', '7', '.', '2', '.', '.', '.', '3', '.'], ['3', '.', '9', '7', '5', '4', '2', '.', '6'], ['.', '.', '.', '.', '.', '.', '.', '9', '.'], 
        ['6', '.', '5', '4', '9', '8', '7', '.', '2'], ['.', '4', '.', '.', '.', '.', '.', '.', '.'], ['8', '.', '4', '6', '7', '5', '1', '.', '3'], ['.', '6', '.', '.', '.', '2', '.', '7', '8'], ['7', '5', '.', '.', '3', '1', '.', '.', '9']]
    print(solveSudoku(board=b))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment