본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1252. Cells with Odd Values in a Matrix

반응형

https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/description/

 

Cells with Odd Values in a Matrix - LeetCode

Can you solve this real interview question? Cells with Odd Values in a Matrix - There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some incre

leetcode.com

행렬 구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. m행 n열의 2차원 vector matrix를 선언해줍니다.2. 정답 변수 oddCnt를 선언해 0으로 초기화합니다.

📔 풀이과정

1. indeices의 원소를 순회하며

  1-1. 0번째 값은 row, 1번째 값은 col이라는 지역변수에 저장해줍니다.

  1-2. row행, col열의 모든 원소를 각각 1씩 증가시켜 줍니다.

2. matrix의 원소를 순회하며 홀수인 값의 개수를 세줍니다.

📔 정답 출력 | 반환

oddCnt를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    int oddCells(int m, int n, vector<vector<int>>& indices) {
        vector <vector<int>> matrix(m,vector<int>(n,0));
        int oddCnt = 0;
        for(auto indice : indices) {
            int row = indice[0];
            int col = indice[1];
            for(int i = 0; i < n; i++) matrix[row][i]++;
            for(int i = 0; i < m; i++) matrix[i][col]++;
        }
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(matrix[i][j] % 2) oddCnt++;
            }   
        }
        return oddCnt;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.