Find if given matrix is Toeplitz 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
< ? php function checkDiagonal ( $ mat , $ i , $ j ) { $ N = 5 ; $ M = 4 ; $ res = $ mat [ $ i ] [ $ j ] ; while ( ++ $ i < $ N && ++ $ j < $ M ) { if ( $ mat [ $ i ] [ $ j ] != $ res ) return false ; } return true ; } function isToepliz ( $ mat ) { $ N = 5 ; $ M = 4 ; for ( $ i = 0 ; $ i < $ M ; $ i ++ ) { if ( ! checkDiagonal ( $ mat , 0 , $ i ) ) return false ; } for ( $ i = 1 ; $ i < $ N ; $ i ++ ) { if ( ! checkDiagonal ( $ mat , $ i , 0 ) ) return false ; } return true ; } $ mat = array ( array ( 6 , 7 , 8 , 9 ) , array ( 4 , 6 , 7 , 8 ) , array ( 1 , 4 , 6 , 7 ) , array ( 0 , 1 , 4 , 6 ) , array ( 2 , 0 , 1 , 4 ) ) ; if ( isToepliz ( $ mat ) ) echo " Matrix ▁ is ▁ a ▁ Toepliz ▁ " ; else echo " Matrix ▁ is ▁ not ▁ a ▁ Toepliz ▁ " ; ? >