260. Same Diagonal Elements
Given a n * n matrix, if each diagonal line from top left to bottom right has the same value you should return true, otherwise return false.
For example:
1,2,3
5,1,2
6,5,1
This test should return true.
But
1,2,3
2,1,5
6,5,1
This test should return false.
Example
Sample 1:
Input: [[1,2,3], [5,1,2], [6,5,1]]
Output: true
Explanation: Each slash from top left to bottom right is the same element, returning true.
Example 2:
Input: [[1,2,3], [2,1,5], [6,5,1]]
Output: false
Explanation: The second slash and the fourth slash are [2, 5]. These two slashes do not satisfy this condition, so return false.
Notice
n within the range is: [1, 500]
Input test data (one parameter per line)How to understand a testcase?
解法1:
这题是判断从对角线(右上到左下)的镜像,这个映像其实不好转换。如果是判断主对角线(左上到右下)的镜像就很容易了(A[i][j]==A[j][i])即可。那怎么转换到主对角线来处理呢?只要把matrix上下翻个个就可以了,即最下面一行跟第一行互换,倒数第二行跟第二行互换,如此反复。
class Solution {
public:
/**
* @param matrix: a matrix
* @return: return true if same.
*/
bool judgeSame(vector<vector<int>> &matrix) {
int n = matrix.size();
vector<vector<int>> symmMatrix(n, vector<int>(n));
reverse(matrix.begin(), matrix.end());
//transpose
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
symmMatrix[i][j] = matrix[j][i];
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (matrix[i][j] != symmMatrix[i][j]) {
return false;
}
}
}
return true;
}
};
解法2:上面的解法好像还是比较慢。看到有人讨论可以把每行和每列求hash值,然后判断。这个方法也不错,应该比较快。
本文探讨了一种算法,用于判断矩阵中从左上至右下的对角线元素是否一致。通过将矩阵翻转并检查其与转置后的镜像是否相等,实现了对特定条件下的矩阵对称性验证。

被折叠的 条评论
为什么被折叠?



