Leetcode 2133. Check if Every Row and Column Contains All Numbers with Python

Alpha, Orderly·2023년 1월 18일
0

leetcode

목록 보기
37/90
post-thumbnail

문제

An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive).

주어진 n * n 의 2차원 배열에서 모든 행과 열이 1 ~ n까지의 숫자를 가지는지 검사하시오.

예시

Input: matrix = [[1,2,3],[3,1,2],[2,3,1]]
Output: true

제한

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 100
  • 1 <= matrix[i][j] <= n

풀이법

스도쿠 풀이 https://velog.io/@ilov1112/Leetcode-37.-Sudoku-Solver-with-Python

에서 썼던 코드중 행과 열 검사 코드만 뽑아와서

사용하면 된다.

class Solution:
    def checkValid(self, matrix: List[List[int]]) -> bool:
        def checker(matrix: List[List[int]], row: int, col: int, size: int):
            r = set()
            c = set()
            for i in range(size):
                if matrix[row][i] in r: return False
                if matrix[i][col] in c: return False
                r.add(matrix[row][i])
                c.add(matrix[i][col])
            return True
        for i in range(len(matrix)):
            if checker(matrix, i, i, len(matrix)) == False: return False
        return True
profile
만능 컴덕후 겸 번지 팬

0개의 댓글