原题:
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模式的 ,是的话返回true,否则false。 这个Toeplitz模式的意思是这个数组从左到右的斜线上的数字是相等的。
思路:判断这一行的所有元素的下一行错位的元素是否和它值相等,然后再判断下一行与下下行错位的值是否相等,以此循环,matrix[row][column]!=matrix[row+1][column+1]则返回false,循环结束返回true,也就是用两个for循环可以实现。
我的程序:
class Solution {
public boolean isToeplitzMatrix(int[][] matrix) {
for(int row=0;row<matrix.length-1;row++)
for(int column=0;column<matrix[0].length-1;column++){
if(matrix[row][column]!=matrix[row+1][column+1])
return false;
}
return true;
}
}
public boolean isToeplitzMatrix(int[][] matrix) {
for(int row=0;row<matrix.length-1;row++)
for(int column=0;column<matrix[0].length-1;column++){
if(matrix[row][column]!=matrix[row+1][column+1])
return false;
}
return true;
}
}