using
System;
using
System.Collections.Generic;
class
Cells {
int
rs;
int
cs;
int
re;
int
ce;
public
Cells(
int
rs,
int
cs,
int
re,
int
ce)
{
this
.rs = rs;
this
.cs = cs;
this
.re = re;
this
.ce = ce;
}
public
override
bool
Equals(Object o)
{
if
(o
is
Cells) {
Cells other = (Cells)o;
return
(rs == other.rs) && (cs == other.cs)
&& (re == other.re) && (ce == other.ce);
}
return
false
;
}
public
override
int
GetHashCode()
{
return
(rs * 100 + cs) * 100 + (re * 100 + ce);
}
}
class
PalindromicPaths {
static
int
R = 3;
static
int
C = 4;
static
int
GetPalindromicPaths(
char
[][] mat)
{
Dictionary<Cells,
int
> memo
=
new
Dictionary<Cells,
int
>();
R = mat.Length;
C = mat[0].Length;
return
GetPalindromicPathsRecur(mat, 0, 0, R - 1,
C - 1, memo);
}
static
int
GetPalindromicPathsRecur(
char
[][] mat,
int
rs,
int
cs,
int
re,
int
ce,
Dictionary<Cells,
int
> memo)
{
if
(rs < 0 || rs >= R || cs < 0 || cs >= C) {
return
0;
}
if
(re < 0 || re < rs || ce < 0 || ce < cs) {
return
0;
}
if
(mat[rs][cs] != mat[re][ce]) {
return
0;
}
if
(Math.Abs((rs - re) + (cs - ce)) <= 1) {
return
1;
}
Cells key =
new
Cells(rs, cs, re, ce);
if
(memo.ContainsKey(key)) {
return
memo[key];
}
int
ret = 0;
ret += GetPalindromicPathsRecur(mat, rs + 1, cs,
re - 1, ce, memo);
ret += GetPalindromicPathsRecur(mat, rs + 1, cs, re,
ce - 1, memo);
ret += GetPalindromicPathsRecur(mat, rs, cs + 1,
re - 1, ce, memo);
ret += GetPalindromicPathsRecur(
mat, rs, cs + 1, re - 1, ce - 1, memo);
memo[key] = ret;
return
ret;
}
public
static
void
Main(
string
[] args)
{
char
[][] mat = {
new
char
[] {
'a'
,
'a'
,
'a'
},
new
char
[] {
'b'
,
'b'
,
'a'
},
new
char
[] {
'a'
,
'a'
,
'a'
},
new
char
[] {
'b'
,
'b'
,
'a'
} };
Console.WriteLine(GetPalindromicPaths(mat));
}
}