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:
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: true
Explanation:
In the above grid, the diagonals are:
“[9]”, “[5, 5]”, “[1, 1, 1]”, “[2, 2, 2]”, “[3, 3]”, “[4]”.
In each diagonal all elements are the same, so the answer is True.
给一个矩阵,判断它是不是Toeplitz矩阵
Toeplitz矩阵指每个对角线方向的元素都相等
思路:
对角线方向是指上一个元素是matrix[r][c],则下一元素是matrix[r+1][c+1]
只需要判断matrix[r][c] 是否和matrix[r-1][c-1]是否相等即可
0行r和0行的c不需要判断
public boolean isToeplitzMatrix(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
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;
}