766. Toeplitz Matrix
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: In the above grid, the diagonals are: "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]". In each diagonal all elements are the same, so the answer is True.
代码如下:
class Solution {
public:
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
//写的太麻烦了,要简单一点的方法
int M=matrix.size();
int N=matrix[0].size();
bool a=1;
bool b=1;
bool c=1;
if (M==1) return c;
if (N==1) return c;
for(int i=0;i<M-1;++i)
{
for(int j=i;j<N-1;++j)
{
if(matrix[i][j]==matrix[i+1][j+1])
a=a*1;
else a=0;
}
}
vector<vector<int>> ssr(N,vector<int>(M));
for(int i=0;i<M;++i)
{
for(int j=0;j<N;++j)
{
ssr[j][i]=matrix[i][j];
}
}
for(int i=0;i< N-1;++i)
{
for(int j=i;j<M-1;++j)
{
if(ssr[i][j]==ssr[i+1][j+1])
b=b*1;
else b=0;
}
}
if(a&&b)
c=1;
else
c=0;
return c;
}
};
简单的思路:
We ask what feature makes two coordinates (r1, c1) and (r2, c2) belong to the same diagonal?
It turns out two coordinates are on the same diagonal if and only if r1 - c1 == r2 - c2.
This leads to the following idea: remember the value of that diagonal as groups[r-c]. If we see a mismatch, the matrix is not Toeplitz; otherwise it is.
判断是否为对角线上的元素需要满足当且仅当r1-c1=r2-c2。所以将行减去列相等的值进行比较,如果相等则表示对角线元素相等,否则不相等。
浙公网安备 33010602011771号