// C# implementation of the above approach
using System;
class GFG
{
// Function to multiply two matrices A and B
static double[,] multiply(double[,] A,
double[,] B, int N)
{
double[,] C = new double[N, N];
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
for (int k = 0; k < N; ++k)
C[i, j] += A[i, k] * B[k, j];
return C;
}
// Function to calculate the power of a matrix
static double[,] matrix_power(double[,] M, int p, int n)
{
double[,] A = new double[n,n];
for (int i = 0; i < n; ++i)
A[i, i] = 1;
while (p > 0)
{
if (p % 2 == 1)
A = multiply(A, M, n);
M = multiply(M, M, n);
p /= 2;
}
return A;
}
// Function to calculate the probability of
// reaching F at time T after starting from S
static double findProbability(double[,] M,
int N, int F, int S, int T)
{
// Storing M^T in MT
double[,] MT = matrix_power(M, T, N);
// Returning the answer
return MT[F - 1, S - 1];
}
// Driver code
public static void Main(String[] args)
{
// Adjacency matrix
// The edges have been stored in the row
// corresponding to their end-point
double[,] G = { { 0, 0.09, 0, 0, 0, 0 },
{ 0.23, 0, 0, 0, 0, 0.62 },
{ 0, 0.06, 0, 0, 0, 0 },
{ 0.77, 0, 0.63, 0, 0, 0 },
{ 0, 0, 0, 0.65, 0, 0.38 },
{ 0, 0.85, 0.37, 0.35, 1.0, 0 } };
// N is the number of states
int N = 6;
int S = 4, F = 2, T = 100;
Console.Write("The probability of reaching " + F +
" at time " + T + "\nafter starting from " +
S + " is {0:F6}",
findProbability(G, N, F, S, T));
}
}
// This code is contributed by 29AjayKumar