A matrix is_Toeplitz_if every diagonal from top-left to bottom-right has the same element.
Now given anM x N
matrix, return True
if and only if the matrix isToeplitz.
Note:
matrix
will be a 2D array of integers.matrix
will have a number of rows and columns in range[1, 20]
.matrix[i][j]
will be integers in range[0, 99]
.
按照要求,一个一个对角线地检查就可以了
class Solution {
public boolean isToeplitzMatrix(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
if(m == 1 || n == 1)
return true;
for(int k = 0; k < n; k++) {
int i = 0;
int j = k;
int num = matrix[i][j];
while(i < m && j < n) {
if(matrix[i][j] != num)
return false;
i++;
j++;
}
}
for(int k = 0; k < m; k++) {
int i = k;
int j = 0;
int num = matrix[i][j];
while(i < m && j < n) {
if(matrix[i][j] != num)
return false;
i++;
j++;
}
}
return true;
}
}