Open In App

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

Last Updated : 01 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
Detailed intuition:

  • 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:

C++
#include <bits/stdc++.h>
using namespace std;

// Helper function to check if a given string is a
// palindrome
bool isPalindrome(const string& path)
{
    int left = 0, right = path.size() - 1;
    while (left < right) {
        if (path[left] != path[right])
            return false;
        left++;
        right--;
    }
    return true;
}

// Helper function to perform DFS and collect all paths
void dfs(const vector<vector<char> >& mat, int x, int y,
         string path, vector<string>& result)
{
    // Add current cell to path
    path += mat[x][y];

    // If we reached the bottom-right cell, check if the
    // path is a palindrome
    if (x == mat.size() - 1 && y == mat[0].size() - 1) {
        if (isPalindrome(path)) {
            result.push_back(path);
        }
        return;
    }

    // Move right
    if (y + 1 < mat[0].size()) {
        dfs(mat, x, y + 1, path, result);
    }

    // Move down
    if (x + 1 < mat.size()) {
        dfs(mat, x + 1, y, path, result);
    }
}

// Main function to find all palindromic paths
vector<string>
findPalindromicPaths(const vector<vector<char> >& mat)
{
    vector<string> result;
    dfs(mat, 0, 0, "", result);
    return result;
}

// Driver code
int main()
{
    vector<vector<char> > mat = { { 'a', 'a', 'a', 'b' },
                                  { 'b', 'a', 'a', 'a' },
                                  { 'a', 'b', 'b', 'a' } };
    vector<string> result = findPalindromicPaths(mat);
    for (const string& path : result) {
        cout << path << endl;
    }
    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

public class PalindromicPaths {

    // Helper function to check if a given string is a
    // palindrome
    private static boolean isPalindrome(String path)
    {
        int left = 0, right = path.length() - 1;
        while (left < right) {
            if (path.charAt(left) != path.charAt(right))
                return false;
            left++;
            right--;
        }
        return true;
    }

    // Helper function to perform DFS and collect all paths
    private static void dfs(char[][] mat, int x, int y,
                            String path,
                            List<String> result)
    {
        // Add current cell to path
        path += mat[x][y];

        // If we reached the bottom-right cell, check if the
        // path is a palindrome
        if (x == mat.length - 1 && y == mat[0].length - 1) {
            if (isPalindrome(path)) {
                result.add(path);
            }
            return;
        }

        // Move right
        if (y + 1 < mat[0].length) {
            dfs(mat, x, y + 1, path, result);
        }

        // Move down
        if (x + 1 < mat.length) {
            dfs(mat, x + 1, y, path, result);
        }
    }

    // Main function to find all palindromic paths
    public static List<String>
    findPalindromicPaths(char[][] mat)
    {
        List<String> result = new ArrayList<>();
        dfs(mat, 0, 0, "", result);
        return result;
    }

    // Driver code
    public static void main(String[] args)
    {
        char[][] mat = { { 'a', 'a', 'a', 'b' },
                         { 'b', 'a', 'a', 'a' },
                         { 'a', 'b', 'b', 'a' } };
        List<String> result = findPalindromicPaths(mat);
        for (String path : result) {
            System.out.println(path);
        }
    }
}
Python
# Helper function to check if a given string is a palindrome.
def is_palindrome(path):
    return path == path[::-1]

# Helper function to perform DFS and collect all paths.


def dfs(mat, x, y, path, result):

    # Add current cell to path
    path += mat[x][y]

    # If we reached the bottom-right cell, check if
    # the path is a palindrome
    if x == len(mat) - 1 and y == len(mat[0]) - 1:
        if is_palindrome(path):
            result.append(path)
        return

    # Move right
    if y + 1 < len(mat[0]):
        dfs(mat, x, y + 1, path, result)

    # Move down
    if x + 1 < len(mat):
        dfs(mat, x + 1, y, path, result)

# Main function to find all palindromic paths.


def find_palindromic_paths(mat):

    result = []
    dfs(mat, 0, 0, "", result)
    return result


# Driver code
if __name__ == "__main__":
    mat = [
        ['a', 'a', 'a', 'b'],
        ['b', 'a', 'a', 'a'],
        ['a', 'b', 'b', 'a']
    ]
    result = find_palindromic_paths(mat)
    for path in result:
        print(path)
C#
using System;
using System.Collections.Generic;

public class PalindromicPaths {

    // Helper function to check if a given string is a
    // palindrome
    private static bool IsPalindrome(string path)
    {
        int left = 0, right = path.Length - 1;
        while (left < right) {
            if (path[left] != path[right])
                return false;
            left++;
            right--;
        }
        return true;
    }

    // Helper function to perform DFS and collect all paths
    private static void Dfs(char[, ] mat, int x, int y,
                            string path,
                            List<string> result)
    {
        // Add current cell to path
        path += mat[x, y];

        // If we reached the bottom-right cell, check if the
        // path is a palindrome
        if (x == mat.GetLength(0) - 1
            && y == mat.GetLength(1) - 1) {
            if (IsPalindrome(path)) {
                result.Add(path);
            }
            return;
        }

        // Move right
        if (y + 1 < mat.GetLength(1)) {
            Dfs(mat, x, y + 1, path, result);
        }

        // Move down
        if (x + 1 < mat.GetLength(0)) {
            Dfs(mat, x + 1, y, path, result);
        }
    }

    // Main function to find all palindromic paths
    public static List<string>
    FindPalindromicPaths(char[, ] mat)
    {
        var result = new List<string>();
        Dfs(mat, 0, 0, "", result);
        return result;
    }

    // Driver code
    public static void Main(string[] args)
    {
        char[, ] mat = { { 'a', 'a', 'a', 'b' },
                         { 'b', 'a', 'a', 'a' },
                         { 'a', 'b', 'b', 'a' } };
        var result = FindPalindromicPaths(mat);
        foreach(var path in result)
        {
            Console.WriteLine(path);
        }
    }
}
JavaScript
// Helper function to check if a given string is a palindrome
function isPalindrome(path) {
    let left = 0, right = path.length - 1;
    while (left < right) {
        if (path[left] !== path[right]) return false;
        left++;
        right--;
    }
    return true;
}

// Helper function to perform DFS and collect all paths
function dfs(mat, x, y, path, result) {
    // Add current cell to path
    path += mat[x][y];

    // If we reached the bottom-right cell, check if the path is a palindrome
    if (x === mat.length - 1 && y === mat[0].length - 1) {
        if (isPalindrome(path)) {
            result.push(path);
        }
        return;
    }

    // Move right
    if (y + 1 < mat[0].length) {
        dfs(mat, x, y + 1, path, result);
    }

    // Move down
    if (x + 1 < mat.length) {
        dfs(mat, x + 1, y, path, result);
    }
}

// Main function to find all palindromic paths
function findPalindromicPaths(mat) {
    let result = [];
    dfs(mat, 0, 0, "", result);
    return result;
}

// Driver code
let mat = [
    ['a', 'a', 'a', 'b'],
    ['b', 'a', 'a', 'a'],
    ['a', 'b', 'b', 'a']
];
let result = findPalindromicPaths(mat);
for (let path of result) {
    console.log(path);
}

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))


 



Next Article

Similar Reads