“托普利兹矩阵”是指如果从左上角到右下角的同一条主斜线上每个元素都相等的矩阵.
给定一个M x N
矩阵,判断是否为“托普利兹矩阵”.
样例
样例 1:
输入: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
输出: True
解释:
1234
5123
9512
在上述矩阵中,主斜线上元素分别为 "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]", 每一条主斜线上元素都相等,所以返回`True`.
样例 2:
输入: matrix = [[1,2],[2,2]]
输出: False
解释:
主斜线 "[1, 2]" 有不同的元素.
注意事项
matrix
是一个二维整数数组.matrix
的行列范围都为[1, 20]
.matrix[i][j]
的整数取值范围为[0, 99]
.
class Solution {
public:
/**
* @param matrix: the given matrix
* @return: True if and only if the matrix is Toeplitz
*/
int m;
int n;
bool isToeplitzMatrix(vector<vector<int>> &matrix) {
// Write your code here
// 先检查主对角线
m = matrix.size();
n = matrix[0].size();
//检查上半部
for(int i = 0; i < n; i++)
{
int count = 1;
while(isarea(count,i+count))
{
if(matrix[count][i + count] != matrix[0][i])
return false;
count++;
}
}
//检查下半部
for(int i = 0; i < m; i++)
{
int count = 1;
while(isarea(i+count,count))
{
if(matrix[i+count][count] != matrix[i][0])
return false;
count++;
}
}
return true;
}
bool isarea(int x, int y)
{
if(x < 0 || y < 0 || x >= m || y >= n)
return false;
return true;
}
};