topic
text
Give you a matrix of mxn. If this matrix is a Toplitz matrix, return true; otherwise, return false.
If the elements on each diagonal from the upper left to the lower right of the matrix are the same, then this matrix is a Toplitz matrix.
Example 1:
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: true
Explanation:
In the above matrix, its diagonal is :
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
All elements on each diagonal are the same, so the answer is True.
Example 2:
Input: matrix = [[1,2],[2,2]]
Output: false
Explanation:
The elements on the diagonal "[1, 2]" are different.
prompt:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 20
0 <= matrix[i][j] <= 99
Advanced:
如果矩阵存储在磁盘上,并且内存有限,以至于一次最多只能将矩阵的一行加载到内存中,该怎么办?
如果矩阵太大,以至于一次只能将不完整的一行加载到内存中,该怎么办?
Source: LeetCode
template
bool isToeplitzMatrix(int** matrix, int matrixSize, int* matrixColSize){
}
Problem solving
analysis
For this question, we need to determine whether the numbers on the diagonal from the upper left to the lower right of the resulting two-digit array are equal.
It can be understood as whether each element and its lower right corner element are equal.
There are not many simple questions, and the official idea is also like this.
Complete source code
bool isToeplitzMatrix(int** matrix, int matrixSize, int* matrixColSize) {
int m = matrixSize, n = matrixColSize[0];
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][j] != matrix[i - 1][j - 1]) {
return false;
}
}
}
return true;
}