Find if given matrix is Toeplitz or not | C ++ program to check whether given matrix is a Toeplitz matrix or not ; Function to check if all elements present in descending diagonal starting from position ( i , j ) in the matrix are all same or not ; mismatch found ; we only reach here when all elements in given diagonal are same ; Function to check whether given matrix is a Toeplitz matrix or not ; do for each element in first row ; check descending diagonal starting from position ( 0 , j ) in the matrix ; do for each element in first column ; check descending diagonal starting from position ( i , 0 ) in the matrix ; we only reach here when each descending diagonal from left to right is same ; Driver code ; Function call
#include <iostream> NEW_LINE using namespace std ; #define N  5 NEW_LINE #define M  4 NEW_LINE bool checkDiagonal ( int mat [ N ] [ M ] , int i , int j ) { int res = mat [ i ] [ j ] ; while ( ++ i < N && ++ j < M ) { if ( mat [ i ] [ j ] != res ) return false ; } return true ; } bool isToepliz ( int mat [ N ] [ M ] ) { for ( int i = 0 ; i < M ; i ++ ) { if ( ! checkDiagonal ( mat , 0 , i ) ) return false ; } for ( int i = 1 ; i < N ; i ++ ) { if ( ! checkDiagonal ( mat , i , 0 ) ) return false ; } return true ; } int main ( ) { int mat [ N ] [ M ] = { { 6 , 7 , 8 , 9 } , { 4 , 6 , 7 , 8 } , { 1 , 4 , 6 , 7 } , { 0 , 1 , 4 , 6 } , { 2 , 0 , 1 , 4 } } ; if ( isToepliz ( mat ) ) cout << " Matrix ▁ is ▁ a ▁ Toepliz ▁ " ; else cout << " Matrix ▁ is ▁ not ▁ a ▁ Toepliz ▁ " ; return 0 ; }