LeetCode 766 Toplitz Matrix HERODING's LeetCode Road

Give you a matrix of mxn. If this matrix is ​​a Toplitz matrix, return true; otherwise, return false.

If the elements on each diagonal from the upper left to the lower right of the matrix are the same, then the matrix is ​​a Toplitz matrix.

Example 1:
Insert picture description here

Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: true
Explanation:
In the above matrix, its diagonal is :
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
All elements on each diagonal are the same, so the answer is True.

Example 2:
Insert picture description here

Input: matrix = [[1,2],[2,2]]
Output: false
Explanation:
The elements on the diagonal "[1, 2]" are different.

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/toeplitz-matrix The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Problem solving idea: The
idea is the same as the official problem solution. It is to judge whether the number except the first row and the first column is equal to the number in the upper left corner. Of course, there are other ideas that traverse from the lower left corner to the upper right corner, but the complexity is also Very high, the code is as follows:

class Solution {
    
    
public:
    bool isToeplitzMatrix(vector<vector<int>>& matrix) {
    
    
        // 定义行列
        int row = matrix.size();
        int col = matrix[0].size();
        // 判断除第一行第一列外的数与左上角的数是否相等
        for(int i = 1; i < row; i ++) {
    
    
            for(int j = 1; j < col; j ++) {
    
    
                if(matrix[i][j] != matrix[i - 1][j - 1]) {
    
    
                    return false;
                }
            }
        }
        return true;
    }
};


/*作者:heroding
链接:https://leetcode-cn.com/problems/toeplitz-matrix/solution/zui-chang-gui-csi-lu-by-heroding-ra0s/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/

Guess you like

Origin blog.csdn.net/HERODING23/article/details/113927910