Find if given matrix is Toeplitz or not | C ++ program to check whether given matrix is a Toeplitz matrix or not ; row = number of rows col = number of columns ; HashMap to store key , value pairs ; If key value exists in the hashmap , ; We check whether the current value stored in this key matches to element at current index or not . If not , return false ; Else we put key , value pair in hashmap ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isToeplitz ( vector < vector < int > > matrix ) { int row = matrix . size ( ) ; int col = matrix [ 0 ] . size ( ) ; map < int , int > Map ; for ( int i = 0 ; i < row ; i ++ ) { for ( int j = 0 ; j < col ; j ++ ) { int key = i - j ; if ( Map [ key ] ) { if ( Map [ key ] != matrix [ i ] [ j ] ) return false ; } else { Map [ i - j ] = matrix [ i ] [ j ] ; } } } return true ; } int main ( ) { vector < vector < int > > matrix = { { 12 , 23 , -32 } , { -20 , 12 , 23 } , { 56 , -20 , 12 } , { 38 , 56 , -20 } } ; string result = ( isToeplitz ( matrix ) ) ? " Yes " : " No " ; cout << result ; return 0 ; }