【LeetCode】766. Toeplitz Matrix(Toeplitz矩阵)
问题描述:
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
Now given an M x N
matrix, return True
if and only if the matrix is Toeplitz.
Example 1:
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]] Output: True Explanation: 1234 5123 9512 In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]", and in each diagonal all elements are the same, so the answer is True.
Example 2:
Input: matrix = [[1,2],[2,2]] Output: False Explanation: The diagonal "[1, 2]" has different elements.
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]
.
思路:对角线上相邻的两个数必须相等才可以是Toeplitz矩阵,那么,就可以遍历这个矩阵,判断两个对角线相邻的数是否不相等,如果不相等,那么他一定就不是Toeplitz矩阵。如果矩阵都满足梁林对角线相等,那么该矩阵就为Toeplitz矩阵。
java
代码:
日期:2018/2/7-12:23
class Solution {
public boolean isToeplitzMatrix(int[][] matrix) {
int m=matrix.length;
int n=matrix[0].length;
for(int i=0;i<m-1;i++) //此处为m-1,n-1的原因是倒数第二个元素就已经判断了是否与下一个元素相等
{
for(int j=0;j<n-1;j++) //即m-2(倒数第二个)是否等于m-1(最后一个)
{
if(matrix[i][j]!=matrix[i+1][j+1])
return false;
}
}
return true;
}
}