[LeetCode] 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:
1234
5123
9512

In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]", and 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].

判断给定二维矩阵是否是Toeplitz矩阵。也就是判断二维矩阵的每组对角线元素是否相等。

首先,以矩阵的第一行为基准,判断以每个元素所在对角线的元素是否相等。

然后,以矩阵的第一列为基准,除去第一个元素,判断每个元素所在对角线的元素是否相等。

最后,如果上述判断都通过,则说明该矩阵是Toeplitz矩阵。

参考代码如下:

class Solution {
public:
    bool isToeplitzMatrix(vector<vector<int>>& matrix) {
        int rows = matrix.size();
        int cols = matrix[0].size();
        for (int j = 0, i = 0; j < cols; j++) {
            int x = i, y = j;
            while (x < rows - 1 && y < cols - 1) {
                if (matrix[x][y] != matrix[x + 1][y + 1])
                    return false;
                x++;
                y++;
            }
        }
        for (int i = 1, j = 0; i < rows; i++) {
            int x = i, y = j;
            while (x < rows - 1 && y < cols - 1) {
                if (matrix[x][y] != matrix[x + 1][y + 1])
                    return false;
                x++;
                y++;
            }
        }
        return true;
    }
};
// 21 ms
原文地址:https://www.cnblogs.com/immjc/p/8327799.html