766. Toeplitz Matrix

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.

Example 2:

Input:
matrix = [
  [1,2],
  [2,2]
]
Output: False
Explanation:
The diagonal "[1, 2]" has different elements.

Note:

  1. matrix will be a 2D array of integers.

  2. matrix will have a number of rows and columns in range [1, 20].

  3. matrix[i][j] will be integers in range [0, 99].

My Solutions:

检查对角线上的数字是不是一致

方法1:从斜切线开始把matrix分为两部分,先检查右上部分是否一致,再检查左下部分是否一致

方法2:检查每个数和它的右下角的数是否一致

class Solution {
    public boolean isToeplitzMatrix(int[][] matrix) {
 
// 方法1
// 右上部分   
//         for (int i = 0; i < matrix.length - 1; i++) {
//             int num = matrix[i][0];
//             int row = i;
//             for (int j = 0; j < matrix[0].length && row < matrix.length; j++) {
//                 if (matrix[row][j] != num) return false;
//                 row++;
//             }
//         }
// 左下部分        
//         for (int j = 1; j < matrix[0].length - 1; j++) {
//             int num = matrix[0][j];
//             int col = j;
//             for (int i = 0; i < matrix.length && col < matrix[0].length; i++) {
//                 if (matrix[i][col] != num) return false;
//                 col++;
//             }
//         }
//         return true;

// 方法2        
        for (int i = 0; i < matrix.length - 1; i++) {
            for (int j = 0; j < matrix[0].length - 1; j++) {
                if (matrix[i][j] != matrix[i + 1][j + 1]) return false;
            }
        }
        return true;
        
    }
}

Last updated