[LeetCode] Toeplitz Matrix

766. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
int n = matrix.size(), m = matrix[0].size();
for(int i = 0; i < m; i++) {
int y = 0, x = i;
while(y + 1 < n and x + 1 < m) {
if(matrix[y][x] != matrix[y+1][x+1]) return false;
y++,x++;
}
}
for(int i = 1; i < n; i++) {
int y = i, x = 0;
while(y + 1 < n and x + 1 < m) {
if(matrix[y][x] != matrix[y+1][x+1]) return false;
y++,x++;
}
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/27/PS/LeetCode/toeplitz-matrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.