본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 766. Toeplitz Matrix

반응형

https://leetcode.com/problems/toeplitz-matrix/description/

 

Toeplitz Matrix - LeetCode

Can you solve this real interview question? Toeplitz Matrix - Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false. A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.   Example 1:

leetcode.com

구현 문제였습니다.

📕 풀이방법

📔 풀이과정

1. 화살표 방향으로 한 번씩 검사해서 모든 대각선이 같은 수로 이루어져 있는지 검사해주면 됩니다.

2. 하나의 대각선 검사는 r행 c열부터 시작해 각자 1씩 증가하며 해주는 함수  isDiagonalNumAllSame를 수행해줍니다.


📕 Code

📔 C++

class Solution {
public:
     bool isDiagonalNumAllSame(int startRow, int startCol, vector<vector<int>>& matrix) {
        int pivNum = matrix[startRow][startCol];
        int r = startRow + 1;
        int c = startCol + 1;
        while(r < matrix.size() && c < matrix[0].size()) {
            if(pivNum != matrix[r][c]) return false;
            r++;
            c++;
        }
        return true;
    }

    bool isToeplitzMatrix(vector<vector<int>>& matrix) {
        for (int r = 0; r < matrix.size(); r++) {
            if (!isDiagonalNumAllSame(r, 0, matrix)) return false;
        }
        for (int c = 1; c < matrix[0].size(); c++) {
            if (!isDiagonalNumAllSame(0, c, matrix)) return false;
        }
        return true;
    }
};

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