Click here to Skip to main content
15,884,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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 left-top to right-bottom diagonal.
All the number in sudoku must appear exactly once in right-top to left-bottom diagonal.
All the number in sudoku must appear exactly once in a square(3*3).
However number can repeat in row or column.


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


Basically I am stuck on the implementation of checking distinct number along diagonal. So my question is how I can make sure that no elements gets repeated in those diagonal and sub-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
Posted
Updated 16-Sep-22 2:30am
v2
Comments
Richard MacCutchan 16-Sep-22 3:09am    
Do you have a question?
Arya Singh 2021 16-Sep-22 4:08am    
Yes I’m stuck on implementation of making sure that no number get repeated along diagonal.
Richard MacCutchan 16-Sep-22 5:31am    
That is not a programming issue. Try creating a diagram on paper and adding the numbers to see how you can figure out what is needed to avoid duplicates.
Arya Singh 2021 16-Sep-22 7:58am    
If I would have been able to do that then why would I ask someone?
Richard MacCutchan 16-Sep-22 8:03am    
You misunderstand the use of this forum. It is here to help fix problems in the code you write, not to do your work for you. This assignment is designed to test your understanding of the lessons you have been given. And if someone here does the work you will not learn anything.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900