Find if given matrix is Toeplitz or not in C++


In this problem, we are given a 2D square matrix mat[][] of size n*n. Our task is to find if the given matrix is Toeplitz or not.

Toeplitz matrix also known as diagonal matrix is a matrix in which the elements at the diagonal start from top-left corner to bottom-right corner.

Let’s take an example to understand the problem,

Input:

          Mat[][] = {{3, 5, 1},
                           {4, 3 ,2},
                           {1, 2, 3}}

Output: Yes

Explanation:  

Diagonal : (0, 0), (1, 1) , (2, 2) has the same value 3.

Solution Approach: 

A simple approach to solve the problem is checking all the elements at a diagonal index. These diagonal values will be indexes where the value of both i and j is the same.

So, we need to check for all i -> 0 to n and j -> 0 to n. If i = j, and mat[i][j] is the same for all.

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
using namespace std;
#define N 4

bool isToeplizMatrix(int mat[N][N])
{
   int diagVal = mat[0][0];
for(int i = 0; i < N ; i++)
   {
      if(mat[i][i] != diagVal){
          return false;
      }
   }
   return true;
}

int main(){

   int mat[N][N] = { { 6, 7, 8, 9 },
                { 4, 6, 7, 8 },
                { 1, 4, 6, 7 },
                { 0, 1, 4, 6 }};

   if (isToeplizMatrix(mat))
      cout<<"Matrix is a Toepliz matrix.";
   else
      cout<<"Matrix is not a Toepliz matrix.";
     
   return 0;
}

Output

Matrix is a Toepliz matrix.

Updated on: 22-Jan-2021

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements