![]() |
VOOZH | about |
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 -> aInput: mat = [['x', 'y']
['y', 'x']]
Output: xyx, xyx
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:
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))