Find if given matrix is Toeplitz or not | Javascript 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
let N = 5 ; let M = 4 ; function checkDiagonal ( mat , i , j ) { let res = mat [ i ] [ j ] ; while ( ++ i < N && ++ j < M ) { if ( mat [ i ] [ j ] != res ) return false ; } return true ; } function isToepliz ( mat ) { for ( let i = 0 ; i < M ; i ++ ) { if ( ! checkDiagonal ( mat , 0 , i ) ) return false ; } for ( let i = 1 ; i < N ; i ++ ) { if ( ! checkDiagonal ( mat , i , 0 ) ) return false ; } return true ; } let mat = [ [ 6 , 7 , 8 , 9 ] , [ 4 , 6 , 7 , 8 ] , [ 1 , 4 , 6 , 7 ] , [ 0 , 1 , 4 , 6 ] , [ 2 , 0 , 1 , 4 ] ] ; if ( isToepliz ( mat ) ) document . write ( " " ) ; else document . write ( " " ) ;