Skip to main content

Sudoku Solver

Problem Statement#

Write a function that accepts a 2D array representing a Sudoku board, and returns true if it is a valid solution, or false otherwise. The cells of the sudoku board may also contain 0's, which will represent empty cells. Boards containing one or more zeroes are considered to be invalid solutions.

The board is always 9 cells by 9 cells, and every cell only contains integers from 0 to 9.

My Solution#

def valid_solution(board):    cols = [0] * 9
    #Verify rows & build columns    for r_ind, row in enumerate(board):        row_total = 0        for c_ind, val in enumerate(row):            cols[c_ind] += val            row_total += val
        if row_total != 45: return False
    # Verify columns    for col in cols:        if col != 45: return False
    # Verify subgrids    for x,y in [(0,3),(3,6),(6,9)]:        for i,j in [(0,3),(3,6),(6,9)]:            subset_sum = sum([sum(item[i:j]) for item in board[x:y]])            if subset_sum != 45: return False
    return True

Top Best Practices#

def validSolution(board):    boxes = validate_boxes(board)    cols = validate_cols(board)    rows = validate_rows(board)    return boxes and cols and rows
def validate_boxes(board):    for i in range(0, 9, 3):        for j in range(0, 9, 3):            nums = board[i][j:j+3] + board[i+1][j:j+3] + board[i+2][j:j+3]            if not check_one_to_nine(nums):                return False    return True
def validate_cols(board):    transposed = zip(*board)    for row in transposed:        if not check_one_to_nine(row):            return False    return True
def validate_rows(board):    for row in board:        if not check_one_to_nine(row):            return False    return True

def check_one_to_nine(lst):    check = range(1,10)    return sorted(lst) == check

Top Clever#

def validSolution(board):    blocks = [[board[x+a][y+b] for a in (0, 1, 2) for b in (0, 1, 2)] for x in (0, 3, 6) for y in (0, 3, 6)]    return not filter(lambda x: set(x) != set(range(1, 10)), board + zip(*board) + blocks)