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