[LeetCode] Check if Every Row and Column Contains All Numbers

아르당·2026년 8월 9일

LeetCode

목록 보기
455/584
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

n x n 행렬은 모든 행과 열이 1부터 n까지 정수를 모두 포함하면 유효하다.
n x n 행렬 matrix가 주어졌을 때, 유효한 행렬이면 true를 반환해라. 그렇지 않으면 false를 반환해라.

Example

#1

Input: matrix = [[1, 2, 3], [3, 1, 2], [2, 3, 1]]
Output: true
Explanation: n = 3이고, 모든 행과 열에 숫자 1, 2, 3을 포함한다.
그래서 true를 반환한다.

#2

Input: matrix = [[1, 1, 1], [1, 2, 3], [1, 2, 3]]
Output: false
Explanation: n = 3이지만, 첫 번째 행과 첫 번째 열에 숫자 2, 3을 포함하지 않는다.
그래서 false를 반환한다.

Constraints

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

Solved

class Solution {
    public boolean checkValid(int[][] matrix) {
        int n = matrix.length;

        for(int i = 0; i < n; i++){
            Set<Integer> rs = new HashSet<>();
            Set<Integer> cs = new HashSet<>();

            for(int j = 0; j < n; j++){
                rs.add(matrix[i][j]);
                cs.add(matrix[j][i]);
            }

            if(rs.size() != n || cs.size() != n){
                return false;
            }
        }

        return true;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글