Skip to content

Latest commit

 

History

History
98 lines (82 loc) · 2.71 KB

36.md

File metadata and controls

98 lines (82 loc) · 2.71 KB
  1. Valid Sudoku
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.


A partially filled sudoku which is valid.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

my thoughts:

1. iterate the board, if the spot is non-empty, build a set of values in its row, col and cell, if the spot value is in the set, return false, else move to next spot. if all spot checks pass, return True.

2. go through 9 rows, 9 cols, 9 cells, if all pass return true.

my solution:

**********99ms
class Solution(object):
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        for i in range(9):
            for j in range(9):
                if board[i][j] != '.':
                    t = board[i][j]
                    row = [
                        board[i][y]
                        for y in range(9)
                        if y != j
                    ]                    
                    col = [
                        board[x][j]
                        for x in range(9)
                        if x != i
                    ]
                    
                    cell = [
                        board[x][y]
                        for x in (i//3*3,i//3*3+1,i//3*3+2)
                        for y in (j//3*3,j//3*3+1,j//3*3+2)
                        if x != i or y != j
                    ]
                    rcc = row + col + cell
                    rcc = set(rcc)
                    if t in rcc:
                        return False
        
        return True
		
		
**********69ms
class Solution(object):
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        for i in range(9):
            ss = set()
            for j in range(9):
                if board[i][j] in ss: return False
                elif board[i][j] != '.':
                    ss.add(board[i][j])
        for j in range(9):
            ss = set()
            for i in range(9):
                if board[i][j] in ss: return False
                elif board[i][j] != '.':
                    ss.add(board[i][j])
        for i in (1, 4, 7):
            for j in (1, 4, 7):
                ss = set()
                for x in (i-1,i,i+1):
                    for y in (j-1,j,j+1):
                        if board[x][y] in ss:
                            return False
                        elif board[x][y] != '.':
                            ss.add(board[x][y])
        return True

my comments:

from other ppl's solution:

1. N/A