LeetCode

托普利茨矩阵

2019-07-18  本文已影响0人  习惯了_就好

如果一个矩阵的每一方向由左上到右下的对角线上具有相同元素,那么这个矩阵是托普利茨矩阵。

给定一个 M x N 的矩阵,当且仅当它是托普利茨矩阵时返回 True。

示例 1:

输入:
matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]
]
输出: True
解释:
在上述矩阵中, 其对角线为:
"[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]范围内。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/toeplitz-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    public boolean isToeplitzMatrix(int[][] matrix) {
        if(matrix == null)return false;
        int row = matrix.length;
        int column = matrix[0].length;
        
        //左下部分
        for(int i = row - 2; i >= 0; i--){
            int tempRow = i + 1;
            int tempColumn = 1;
            while(tempRow < row && tempColumn < column){
                if(matrix[i][0] != matrix[tempRow][tempColumn]){
                    return false;
                } else {
                    tempRow++;
                    tempColumn++;
                }
            }
        }
        
        //右上部分
        for(int i = 1; i < column; i++){
            int tempRow = 1;
            int tempColumn = i + 1;
            while(tempColumn < column && tempRow < row){
                if(matrix[0][i] != matrix[tempRow][tempColumn]){
                    return false;
                } else {
                    tempRow++;
                    tempColumn++;
                }
            }
        }
        
        return true;
    }
}
上一篇下一篇

猜你喜欢

热点阅读