LintCode 260: Same Diagonal Elements

本文探讨了一种算法,用于判断矩阵中从左上至右下的对角线元素是否一致。通过将矩阵翻转并检查其与转置后的镜像是否相等,实现了对特定条件下的矩阵对称性验证。

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值,然后判断。这个方法也不错,应该比较快。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值