Toeplitz Matrix

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.

Example:

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.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

bool isToeplitzMatrix(vector<vector<int>> &matrix)
{
    int n = matrix.size();
    if (n == 0)
        return true;
    int m = matrix[0].size();

    int k = 0;
    while (true)
    {
        int i = 0j = k;
        while (i < n && j < m)
        {
            if (matrix[i][j] != matrix[0][k])
                return false;
            i++;
            j++;
        }
        k++;
        if (k >= m)
            break;
    }

    k = 1;
    while (true)
    {
        int i = k;
        int j = 0;
        while (i < n && j < m)
        {
            if (matrix[i][j] != matrix[k][0])
                return false;
            i++;
            j++;
        }
        k++;
        if (k >= n)
            break;
    }
    return true;
}

int main()
{
    vector<vector<int>> matrix = {{1234},
                                  {5123},
                                  {9512}};

    if (isToeplitzMatrix(matrix))
        cout << "true";
    else
        cout << "false";

    return 0;
}


No comments:

Post a Comment