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


In this problem, we are given a matix which contains aplhabets (lowercase only) and we have to print all palidromic paths in the given matrix from top left to bottom right of the matrix.

Allowed moves in this problem are right and down. Diagonal moves are not allowed.

Let’s take an example to understand the problem −

Input: matrix[][] ={
   {"xxxy",
   "yxxx",
   "xyyx"}
Output: xxxxxx , xxxxxx , xyxxyx

Explaination

Lets see all valid moves from top left to bottom right using the position wrt to ith position.

i00 -> i01 -> i02 -> i03 -> i13 -> i23 = xxxyxx
i00 -> i01 -> i11 -> i12 -> i13 -> i23 = xxxxxx
.
.
.
i00 -> i10 -> i20 -> i21 -> i22 -> i23 = xyxyyx

Out of all possible outcomes, we need only palindromic path as outcomes that are −

i00 -> i01 -> i11 -> i12 -> i13 -> i23 = xxxxxx
i00 -> i01 -> i02 -> i12 -> i13 -> i23 = xxxxxx
i00 -> i10 -> i11 -> i12 -> i22 -> i23 = xyxxyx

In the explanation itself, we have laid the base of the solution to the problem. We will find all paths from top-left to bottom-right and print all those which give results to palindromic path.

Example

The example below will illustrate the solution −

 Live Demo

#include<iostream>
using namespace std;
#define N 4
int printPalindrome(string str){
   int len = str.length() / 2;
   for (int i = 0; i < len; i++) {
      if (str[i] != str[str.length() - i - 1])
      return 0;
   }
   cout<<str<<endl;
}
void findPath(string str, char a[][N], int i, int j, int m, int n) {
   if (j < m - 1 || i < n - 1) {
      if (i < n - 1)
      findPath(str + a[i][j], a, i + 1, j, m, n);
      if (j < m - 1)
      findPath(str + a[i][j], a, i, j + 1, m, n);
   } else {
      str = str + a[n - 1][m - 1];
      printPalindrome(str) ;
   }
}
int main() {
   char matrix[][N] = {
      { 'x', 'y', 'x', 'y' },
      { 'y', 'x', 'x', 'y' },
      { 'y', 'x', 'y', 'x' }
   };
   string str = "";
   cout<<"Palimdromic path are : ";
   findPath(str, matrix, 0, 0, 4, 3);
   return 0;
}

Output

Palimdromic path are : xyxxyx
xyxxyx
xyxxyx
xyxxyx
xyxxyx
xyxxyx
xyxxyx
xyxxyx

Updated on: 14-Jul-2020

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements