Categories:

Tags:



Problem

Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 20
  • 0 <= matrix[i][j] <= 99

Solution

The problem Toeplitz Matrix can be solved by iterating through all rows and checking if each element is identical to the previous diagonal element.

Implementation

static const int fast_io = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution
{
  public:
    bool isToeplitzMatrix(vector<vector<int>> &matrix)
    {
        for (int i = 1; i < matrix.size(); i++)
            for (int j = 1; j < matrix[i].size(); j++)
                if (matrix[i][j] != matrix[i - 1][j - 1])
                    return false;

        return true;
    }
};