Find if given matrix is Toeplitz or not | JAVA 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
import java . util . * ; class GFG { static boolean isToeplitz ( int [ ] [ ] matrix ) { int row = matrix . length ; int col = matrix [ 0 ] . length ; HashMap < Integer , Integer > map = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < row ; i ++ ) { for ( int j = 0 ; j < col ; j ++ ) { int key = i - j ; if ( map . containsKey ( key ) ) { if ( map . get ( key ) != matrix [ i ] [ j ] ) return false ; } else { map . put ( i - j , matrix [ i ] [ j ] ) ; } } } return true ; } public static void main ( String [ ] args ) { int [ ] [ ] matrix = { { 12 , 23 , - 32 } , { - 20 , 12 , 23 } , { 56 , - 20 , 12 } , { 38 , 56 , - 20 } } ; String result = ( isToeplitz ( matrix ) ) ? " Yes " : " No " ; System . out . println ( result ) ; } }