LeetCode 题解(231) : Valid Sudoku

来源:互联网 发布:数据挖掘看什么书 编辑:程序博客网 时间:2024/05/01 06:50

题目:

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.

题解:

C++和Java版略显笨重,这里就不给出了。Python版如下

class Solution(object):    def isValidSudoku(self, board):        """        :type board: List[List[str]]        :rtype: bool        """        rows, cols, cells = [[] for i in range(9)], [[]for i in range(9)], [[] for i in range(9)]        for i in range(len(board)):            for j in range(len(board[0])):                e = board[i][j]                if e != '.':                    if e in rows[i] or e in cols[j] or e in cells[(i / 3) * 3 + j / 3]:                        return False                    else:                        rows[i].append(e)                        cols[j].append(e)                        cells[(i / 3 * 3 + j / 3)].append(e)        return True                    

0 0