반응형
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;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 819. Most Common Word (0) | 2023.07.21 |
---|---|
(C++) - LeetCode (easy) 806. Number of Lines To Write String (0) | 2023.07.17 |
(C++) - LeetCode (easy) 762. Prime Number of Set Bits in Binary Representation (0) | 2023.07.10 |
(C++) - LeetCode (easy) 748. Shortest Completing Word (0) | 2023.07.07 |
(C++) - LeetCode (easy) 747. Largest Number At Least Twice of Others (0) | 2023.07.04 |