VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-palindromic-paths-top-left-bottom-right-matrix/

⇱ Print all palindromic paths from top left to bottom right in a matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print all palindromic paths from top left to bottom right in a matrix

Last Updated : 1 Jul, 2024

Given a m*n matrix mat[][] containing only lowercase alphabetical characters, the task is to print all palindromic paths from the top-left cell to the bottom-right cell. A path is defined as a sequence of cells starting from the top-left and ending at the bottom-right, and we can only move right or down from any cell.

Example:

Input: mat = [['a', 'a', 'a', 'b'],
['b', 'a', 'a', 'a'],
['a', 'b', 'b', 'a']]
Output: aaaaaa, aaaaaa, abaaba
Explanation:

  • Path 1:a -> a -> a -> a -> a -> a
  • Path 2:a -> a -> a -> a -> a -> a
  • Path 3:a -> b -> a-> a -> b -> a

Input: mat = [['x', 'y']
['y', 'x']]
Output: xyx, xyx

Recursive approach to Print all palindromic paths from top left to bottom right in a matrix:

Explore all possible paths from the top-left cell to the bottom-right cell, and check if each path forms a palindrome.

  • Start at the top-left cell.
  • Move either right or down to explore all paths recursively.
  • Store the current path in a list.
  • When the bottom-right cell is reached, check if the path is a palindrome.
  • If the path is a palindrome, add it to the result list.

Code Implementation:


Output
aaaaaa
aaaaaa
abaaba

Time Complexity: O(m*n*2(m+n)), The number of paths in an m x n matrix is exponential because at each step, we have two choices: move right or move down.
Auxiliary Space: O(m*n*2(m+n))


Comment
Article Tags:
Article Tags: