Count of odd length contiguous Palindromic sequences in a Matrix | Python code to Count the odd length contiguous Palindromic sequences in the matrix ; Function to count the number of contiguous palindromic sequences in the matrix ; Add the total number of elements in the matrix to the count ; Length of possible sequence to be checked for palindrome horizontally and vertically ; Iterate through each element of the matrix and count the number of palindromic sequences in each row and column ; Find the possible length of sequences that can be a palindrome ; From i , check if the sequence formed by elements to its left and right is palindrome or not ; if the sequence [ i , j - k ] to [ i , j + k ] is a palindrome , increment the count by 1 ; From i , check if the sequence formed by elements to its above and below is palindrome or not ; if the sequence [ i - k , j ] to [ i + k , j ] is a palindrome , increment the count by 1 ; Return the total count of the palindromic sequences ; Driver code
MAX = 10 ; NEW_LINE def countPalindromes ( n , m , matrix ) : NEW_LINE INDENT count = n * m ; NEW_LINE length_of_sequence_row = 0 ; NEW_LINE length_of_sequence_column = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT length_of_sequence_row = min ( j , m - 1 - j ) ; NEW_LINE length_of_sequence_column = min ( i , n - i - 1 ) ; NEW_LINE for k in range ( 1 , length_of_sequence_row + 1 ) : NEW_LINE INDENT if ( matrix [ i ] [ j - k ] == matrix [ i ] [ j + k ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT for k in range ( 1 , length_of_sequence_column + 1 ) : NEW_LINE INDENT if ( matrix [ i - k ] [ j ] == matrix [ i + k ] [ j ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 3 ; NEW_LINE n = 3 ; NEW_LINE matrix = [ 2 , 1 , 2 ] , [ 1 , 1 , 1 ] , [ 2 , 1 , 2 ] ; NEW_LINE print ( countPalindromes ( n , m , matrix ) ) ; NEW_LINE DEDENT