Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sudoku Solver in Python #326

Open
AzureBarrage opened this issue May 12, 2023 · 2 comments
Open

Sudoku Solver in Python #326

AzureBarrage opened this issue May 12, 2023 · 2 comments

Comments

@AzureBarrage
Copy link

The application utilizes two main functions, is_valid_move(grid, row, col, number) and solve_sudoku(grid, row, col), which together can solve a given Sudoku puzzle.

is_valid_move(grid, row, col, number) This function checks if placing a given number at a specific row and col in the grid is a valid move according to the rules of Sudoku. It returns True if the move is valid, and False otherwise.

solve_sudoku(grid, row, col) This function attempts to solve the Sudoku puzzle represented by the grid using a recursive backtracking algorithm. It returns True if a solution is found, and False otherwise.

@github-actions
Copy link

Message that will be displayed on users first issue

@AzureBarrage
Copy link
Author

def is_valid_move(grid, row, col, number):
    if number in grid[row]:  # Check row
        return False

    if number in [grid[r][col] for r in range(9)]:  # Check column
        return False

    # Check 3x3 box
    box_row, box_col = row - row % 3, col - col % 3
    for r in range(3):
        for c in range(3):
            if grid[box_row + r][box_col + c] == number:
                return False

    return True


def solve_sudoku(grid, row, col):
    if col == 9:
        if row == 8:
            return True
        row += 1
        col = 0

    if grid[row][col] > 0:
        return solve_sudoku(grid, row, col + 1)

    for num in range(1, 10):
        if is_valid_move(grid, row, col, num):
            grid[row][col] = num
            if solve_sudoku(grid, row, col + 1):
                return True

        grid[row][col] = 0

    return False


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

if solve_sudoku(grid, row=0, col=0):
    for row in grid:
        print(' '.join(map(str, row)))
else:
    print("No solution for this Sudoku puzzle")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant