How to solve diagonally constraint sudoku?

Viewed 56

Write a program to solve a Sudoku puzzle by filling the empty cells where 0 represent empty cell.

Rules:

  • All the number in sudoku must appear exactly once in diagonal running from top-left to bottom-right.
  • All the number in sudoku must appear exactly once in diagonal running from top-right to bottom-left.
  • All the number in sudoku must appear exactly once in a 3*3 sub-grid.

However number can repeat in row or column.

Constraints: N = 9; where N represent rows and column of grid.

What I have tried:

N = 9
def printing(arr):
    for i in range(N):
        for j in range(N):
            print(arr[i][j], end=" ")
        print()


def isSafe(grid, row, col, num):
    for x in range(9):
        if grid[x][x] == num:
            return False
    cl = 0
    for y in range(8, -1, -1):
        if grid[cl][y] == num:
            cl += 1
            return False
    startRow = row - row % 3
    startCol = col - col % 3
    for i in range(3):
        for j in range(3):
            if grid[i + startRow][j + startCol] == num:
                return False
    return True


def solveSudoku(grid, row, col):
    if (row == N - 1 and col == N):
        return True
    if col == N:
        row += 1
        col = 0
    if grid[row][col] > 0:
        return solveSudoku(grid, row, col + 1)
    for num in range(1, N + 1, 1):
        if isSafe(grid, row, col, num):
            grid[row][col] = num
            print(grid)
            if solveSudoku(grid, row, col + 1):
                return True
        grid[row][col] = 0
    return False
if (solveSudoku(grid, 0, 0)):
    printing(grid)
else:
    print("Solution does not exist")

Input:

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

Output:

8 3 7 0 4 2 1 2 4
5 0 6 1 8 6 3 6 7 
4 1 2 7 3 5 5 0 8 
2 8 3 5 4 8 6 0 5 
6 5 0 0 7 1 2 1 7 
1 4 7 3 2 6 8 4 3 
7 8 1 4 1 6 3 5 0 
6 2 3 7 3 5 7 4 2 
0 5 4 2 8 0 6 8 1

Basically I am stuck on the implementation of checking distinct number along diagonal. So question is how I can make sure that no elements gets repeated in those diagonal and sub-grid.

0 Answers
Related