Valid Sudoku
이 문제는 제공된 9x9 matrix sudoku 문제가 valid 한지 안한지 리턴하는 문제 입니다.
This is the problem to check whether given matrix is valid or not
이 경우는 간단히 O(N^2) 을 써서 사용했습니다. valid 한 조건의 경우
row, col, box에 같은 변수값이 있는지 없는지로 추가하였습니다.
for solving problem i use that way that is looping given matrix and if the value is exists checking that value is valid or not. if the result is invalid then return False. and if don’t found a any invalid value in loop matrix then return True.
Python
class Solution:
def is_valid(self, board, row, col, num):
"""
This is the function to checking given num is valid or not.
return: boolean
"""
# TODO: checking row is valid
for x in range(9):
if x != col and board[row][x] == num:
return False
# TODO: chcking colum in valid
for x in range(9):
if x != row and board[x][col] == num:
return False
# TODO: checking box is valid
startRow = row - row % 3
startCol = col - col % 3
for i in range(3):
for j in range(3):
if (
i + startRow != row and
j + startCol != col and
board[i + startRow][j + startCol] == num
):
return False
return True
def isValidSudoku(self, board: List[List[str]]) -> bool:
for i in range(9):
for j in range(9):
if board[i][j] == '.':
continue
if not self.is_valid(board, i, j, board[i][j]):
return False
return True
댓글 없음:
댓글 쓰기