using System;
using System.Collections.Generic;
class Program
{
const int INF = 100000000;
static char[,] mat = new char[1000, 1000];
static int[,] dis = new int[1000, 1000];
// Initialize the distance matrix with INF values
static void Init(int m, int n)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
dis[i, j] = INF;
}
}
}
// Perform Breadth-First Search to find the shortest path
static void BFS(int startX, int startY, int m, int n)
{
dis[startX, startY] = 0;
Queue<Tuple<int, int>> dq = new Queue<Tuple<int, int>>();
Tuple<int, int> p = Tuple.Create(startX, startY);
dq.Enqueue(p);
// BFS traversal
while (dq.Count > 0)
{
p = dq.Dequeue();
int x = p.Item1;
int y = p.Item2;
int[] a = { 0, -1, 0, 1 };
int[] b = { -1, 0, 1, 0 };
// Explore neighbors
for (int i = 0; i < 4; i++)
{
int tempX = x + a[i];
int tempY = y + b[i];
// Check if the neighbor is within the matrix bounds
if (InRange(tempX, tempY, m, n))
{
// If the neighbor has the same character and a shorter distance, update and add to
// the front of the queue
if (mat[tempX, tempY] == mat[x, y] && dis[tempX, tempY] > dis[x, y])
{
dq.Enqueue(Tuple.Create(tempX, tempY));
dis[tempX, tempY] = dis[x, y];
}
// If the neighbor has a different character and a shorter distance, update and add to
// the back of the queue
else if (mat[tempX, tempY] != mat[x, y])
{
if (dis[tempX, tempY] > dis[x, y] + 1)
{
dq.Enqueue(Tuple.Create(tempX, tempY));
dis[tempX, tempY] = dis[x, y] + 1;
}
}
}
}
}
}
// Check if the position is within the matrix bounds
static bool InRange(int x, int y, int m, int n)
{
return x >= 0 && x < m && y >= 0 && y < n;
}
// Display the matrix and distance matrix
static void Display(int m, int n)
{
// Display the matrix
Console.WriteLine("Matrix:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(mat[i, j] + " ");
}
Console.WriteLine();
}
// Display the distance matrix
Console.WriteLine("Distance Matrix:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(dis[i, j] + " ");
}
Console.WriteLine();
}
}
static void Main()
{
// Static input
int m = 2, n = 3;
char[,] matStatic = { { 'a', 'b', 'n' }, { 'd', 'e', 'f' } };
// Copy the static input to the global matrix
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
mat[i, j] = matStatic[i, j];
}
}
// Initialize and perform BFS
Init(m, n);
BFS(0, 0, m, n);
// Output the result
Console.WriteLine("Shortest Path Distance: " + dis[m - 1, n - 1]);
}
}
// This code is contributed by shivamgupta0987654321