Valid Sudoku in Python



Suppose we have one 9x9 Sudoku board. 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 (3x3) sub-boxes of the grid must contain the digits from 1-9 without repetition.

Suppose the Sudoku grid is like −

53

7



6

195



98



6
8


6


3
4

8
3

1
7

2



6

6



28



419

5




8

79

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

Example(Python)

Let us see the following implementation to get better understanding −

class Solution(object):
   def isValidSudoku(self, board):
      """
      :type board: List[List[str]]
      :rtype: bool
      """
      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