using System;
using System.Collections.Generic;
class MainClass
{
// Using a Dictionary for mp1 and mp2 in C#
static Dictionary<string, int> mp1 = new Dictionary<string, int>();
static Dictionary<string, int> mp2 = new Dictionary<string, int>();
// Backtracking function for the left part
static void Part1(int i, int j, int cnt, int zor, int[][] a, int n, int m)
{
if (cnt <= 0)
{
// Count the number of triplets
string key = $"{zor},{i},{j}";
if (!mp1.ContainsKey(key)) mp1[key] = 0;
mp1[key]++;
return;
}
// Move rightwards
if (j + 1 < m)
{
Part1(i, j + 1, cnt - 1, zor ^ a[i][j + 1], a, n, m);
}
// Move downwards
if (i + 1 < n)
{
Part1(i + 1, j, cnt - 1, zor ^ a[i + 1][j], a, n, m);
}
}
// Backtracking function for the right part
static void Part2(int i, int j, int cnt, int zor, int[][] a, int n, int m)
{
if (cnt <= 0)
{
// Count the number of triplets
string key = $"{zor},{i},{j}";
if (!mp2.ContainsKey(key)) mp2[key] = 0;
mp2[key]++;
return;
}
// Move leftwards
if (j - 1 >= 0)
{
Part2(i, j - 1, cnt - 1, zor ^ a[i][j - 1], a, n, m);
}
// Move upwards
if (i - 1 >= 0)
{
Part2(i - 1, j, cnt - 1, zor ^ a[i - 1][j], a, n, m);
}
}
// Function to count the paths with XOR K
static int CountPaths(int N, int M, int K, int[][] a)
{
int ans = 0;
int n = N;
int m = M;
int k = K;
int cnt1 = (n + m - 2) / 2;
int cnt2 = (n + m - 2) - cnt1;
// Edge case: matrix is 1x1 and the only element is k
if (n == 1 && m == 1 && a[0][0] == k)
{
return 1;
}
Part1(0, 0, cnt1, a[0][0], a, n, m);
Part2(n - 1, m - 1, cnt2 - 1, a[n - 1][m - 1], a, n, m);
foreach (var item in mp2)
{
var split = item.Key.Split(',');
int zor = int.Parse(split[0]);
int idx = int.Parse(split[1]);
int j = int.Parse(split[2]);
int cnt = item.Value;
int required = k ^ zor;
if ((idx - 1) >= 0 && mp1.ContainsKey($"{required},{idx - 1},{j}"))
{
ans += cnt * mp1[$"{required},{idx - 1},{j}"];
}
if ((j - 1) >= 0 && mp1.ContainsKey($"{required},{idx},{j - 1}"))
{
ans += cnt * mp1[$"{required},{idx},{j - 1}"];
}
}
return ans;
}
public static void Main(string[] args)
{
int[][] a = new int[3][]
{
new int[] { 2, 1, 5 },
new int[] { 7, 10, 0 },
new int[] { 12, 6, 4 }
};
int ans = CountPaths(3, 3, 11, a);
Console.WriteLine(ans); // Output: 3
}
}