只要比较每一行的[0,n-1]与后一行的[1,n]是否完全一致即可,n为行的长度。
package T766托普利茨矩阵;
public class Solution {
public boolean isToeplitzMatrix(int[][] matrix) {
if (matrix.length == 1) {
return true;
}
int[] lastLine = matrix[0];
for (int i = 1; i < matrix.length; i++) {
for (int j = 0; j < lastLine.length - 1; j++) {
if (lastLine[j] != matrix[i][j + 1]) {
return false;
}
}
lastLine = matrix[i];
}
return true;
}
}
```
class Solution:
def isToeplitzMatrix(self, matrix) -> bool:
if len(matrix) == 1:
return True
for i in range(1, len(matrix)):
if matrix[i - 1][:-1] == matrix[i][1:]:
continue
else:
return False
return True
if __name__ == '__main__':
x = Solution()
matrix = [
[1, 2, 3, 4],
[5, 1, 2, 3],
[9, 5, 1, 2]
]