leetcode 766. Toeplitz Matrix(託普利茨矩陣)
阿新 • • 發佈:2021-01-13
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:
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;
}