Program to validate a sudoku grid is solvable or not in Python



Suppose we have one 9×9 Sudoku grid. We have to check whether that is valid or now. Only the filled cells need to be validated according to the following rules −

  • Each row must contain the digits from 1−9 without repetition.

  • Each column must contain the digits from 1−9 without repetition.

  • Each of the 9 (3−3) sub−boxes of the grid must contain the digits from 1−9 without repetition.

Suppose the Sudoku grid is like −

This is valid.

To solve this, we will follow these steps −

  • for i in range 0 to 8

    • create some empty dictionary called row, col and block, row_cube := 3 * (i / 3), and col_cube := 3 * (i mod 3)

    • for j in range 0 to 8

      • if board[i, j] is not blank and board[i, j] in row, then return false

      • row[board[i, j]] := 1

      • if board[j, i] is not blank and board[j, i] in col, then return false

      • col[board[j, i]] := 1

      • rc := row_cube + j/3 and cc := col_cube + j mod 3

      • if board[rc, cc] in block and board[rc, cc] is not blank, then return false

      • block[board[rc, cc]] := 1

  • return true

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def isValidSudoku(self, board):
      for i in range(9):
         row = {}
         column = {}
         block = {}
         row_cube = 3 * (i//3)
         column_cube = 3 * (i%3)
         for j in range(9):
            if board[i][j]!='.' and board[i][j] in row:
               return False
            row[board[i][j]] = 1
            if board[j][i]!='.' and board[j][i] in column:
               return False
            column[board[j][i]] = 1
            rc= row_cube+j//3
            cc = column_cube + j%3
            if board[rc][cc] in block and board[rc][cc]!='.':
               return False
            block[board[rc][cc]]=1
         return True
ob1 = Solution()
print(ob1.isValidSudoku([
["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"]]))

Input

[
["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"]]

Output

True

Advertisements