// C# program for the above approach
using System;
class GFG
{
// Function to find the maximum product
// from the top left and bottom right
// cell of the given matrix grid[][]
static int maxProductPath(int[,] grid)
{
// Store dimension of grid
int n = grid.GetLength(0);
int m = grid.GetLength(1);
// Stores maximum product path
int[,] maxPath = new int[n, m];
// Stores minimum product path
int[,] minPath = new int[n, m];
// Traverse the grid and update
// maxPath and minPath array
for(int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
// Initialize to inf and -inf
int mn = Int32.MaxValue;
int mx = Int32.MinValue;
// Base Case
if(i == 0 && j == 0)
{
mx = grid[i, j];
mn = grid[i, j];
}
// Calculate for row:
if(i > 0)
{
int tempmx = Math.Max((maxPath[i - 1, j] *
grid[i, j]),
(minPath[i - 1, j] *
grid[i, j]));
// Update the maximum
mx = Math.Max(mx, tempmx);
int tempmn = Math.Min((maxPath[i - 1, j] *
grid[i, j]),
(minPath[i - 1, j] *
grid[i, j]));
// Update the minimum
mn = Math.Min(mn, tempmn);
}
// Calculate for column
if(j > 0)
{
int tempmx = Math.Max((maxPath[i, j - 1] *
grid[i, j]),
(minPath[i, j - 1] *
grid[i, j]));
// Update the maximum
mx = Math.Max(mx, tempmx);
int tempmn = Math.Min((maxPath[i, j - 1] *
grid[i, j]),
(minPath[i, j - 1] *
grid[i,j]));
// Update the minimum
mn = Math.Min(mn, tempmn);
}
// Update maxPath and minPath
maxPath[i,j] = mx;
minPath[i,j] = mn;
}
}
// If negative product
if(maxPath[n - 1, m - 1] < 0)
{
return -1;
}
// Otherwise
else
{
return(maxPath[n - 1, m - 1]);
}
}
// Driver Code
static public void Main ()
{
// Given matrix mat[][]
int[,] mat={{1, -2, 1}, {1, -2, 1}, {3, -4, 1}};
// Function Call
Console.WriteLine(maxProductPath(mat));
}
}
// This code is contributed by avanitrachhadiya2155