[LeetCode] Special Positions in a Binary Matrix

아르당·2026년 5월 31일

LeetCode

목록 보기
332/583
post-thumbnail

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

Problem

m x n 이진 행렬 mat이 주어졌을 때, mat에서 특별한 위치에 있는 수를 반환해라.

위 (i, j)가 mat[i][j] == 1이고 i번째 행과 j번째 열의 다른 모든 원소가 0인 경우 특별한 위라고 한다.

Example

#1

Input: mat = [[1, 0, 0], [0, 0, 1], [1, 0, 0]]
Output: 1
Explanation: (1, 2)은 mat[1][2] == 1이고 1행과 2열의 다른 모든 요소가 0이기 때문에 특별한 위치이다.

#2

Input: mat = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
Output: 3
Explanation: (0, 0), (1, 1), (2, 2)는 특별한 위치이다.

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • mat[i][j]는 0 또는 1 둘 중 하나이다.

Solved

class Solution {
    public int numSpecial(int[][] mat) {
        int special = 0;

        for(int[] row : mat){
            if(getRowSum(row) == 1){
                int colIdx = getIndexOfOne(row);
                special += (getColumnSum(mat, colIdx) == 1) ? 1 :0;
            }
        }

        return special;
    }

    private int getRowSum(int[] row){
        int sum = 0;

        for(int num : row){
            sum += num;
        }

        return sum;
    }

    private int getColumnSum(int[][] mat, int colIdx){
        int sum = 0;

        for(int[] row : mat){
            sum += row[colIdx];
        }

        return sum;
    }

    private int getIndexOfOne(int[] row){
        for(int i = 0; i < row.length; i++){
            if(row[i] == 1){
                return i;
            }
        }

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

0개의 댓글