Question:

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.

如果从左上角到右下角的每个对角线具有相同的元素,则矩阵是Toeplitz。
现在给出一个Mxn矩阵,当且仅当矩阵是Toeplitz时返回真。

Example:

  1. Input:
  2. matrix = [
  3. [1,2,3,4],
  4. [5,1,2,3],
  5. [9,5,1,2]
  6. ]
  7. Output:
  8. True
  9. Explanation:
  10. In the above grid, the diagonals are:
  11. "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
  12. In each diagonal all elements are the same, so the answer is True.
  1. Input:
  2. matrix = [
  3. [1,2],
  4. [2,2]
  5. ]
  6. Output:
  7. False
  8. Explanation:
  9. The diagonal "[1, 2]" has different elements.

Solution:

  1. var isToeplitzMatrix = function(matrix) {
  2. for (let i= 0; i < matrix.length -1 ; i++ ){
  3. for (let j = 0 ; j< matrix[0].length-1;j++){
  4. if(matrix[i][j] !== matrix[i+1][j+1]){
  5. return false;
  6. }
  7. }
  8. }
  9. return true
  10. };