// C# program to find maximum area of triangle
// having different vertex color in a matrix.
using System;
class MainClass {
const int R = 4;
const int C = 5;
// return the color value so that their corresponding
// index can be access.
static int mapcolor(char c)
{
if (c == 'r') {
return 0;
}
else if (c == 'g') {
return 1;
}
else if (c == 'b') {
return 2;
}
else {
return -1;
}
}
// Returns the maximum area of triangle from all
// the possible triangles
static double findarea(char[, ] mat, int r, int c,
int[, ] top, int[, ] bottom,
int[] left, int[] right)
{
double ans = .0;
// for each column
for (int i = 0; i < c; i++) {
// for each top vertex
for (int x = 0; x < 3; x++) {
// for each bottom vertex
for (int y = 0; y < 3; y++) {
// finding the third color of
// vertex either on right or left.
int z = 3 - x - y;
// finding area of triangle on left side
// of column.
if (x != y
&& top[x, i]
!= int.MaxValue&&
bottom[y, i]
!= int.MinValue&& left[z]
!= int.MaxValue) {
ans = Math.Max(
ans,
(1.0 / 2.0)
* (bottom[y, i] - top[x, i])
* (i - left[z]));
}
// finding area of triangle on right
// side of column.
if (x != y
&& top[x, i]
!= int.MaxValue&&
bottom[y, i]
!= int.MinValue&& right[z]
!= int.MinValue) {
ans = Math.Max(
ans,
(1.0 / 2.0)
* (bottom[y, i] - top[x, i])
* (right[z] - i)+4);
}
}
}
}
return ans;
}
// Precompute the vertices of top, bottom, left
// and right and then computing the maximum area.
static double maxarea(char[, ] mat, int r, int c)
{
int[] left
= { int.MaxValue, int.MaxValue, int.MaxValue };
int[] right
= { int.MinValue, int.MinValue, int.MinValue };
int[, ] top = new int[3, C];
int[, ] bottom = new int[3, C];
// finding the r, b, g cells for the left
// and right vertices.
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
int color = mapcolor(mat[i, j]);
if (color != -1) {
left[color] = Math.Min(left[color], j);
right[color]
= Math.Max(right[color], j);
}
}
}
// finding set of {r, g, b} of top and
// bottom for each column.
for (int j = 0; j < c; j++) {
for (int i = 0; i < r; i++) {
int color = mapcolor(mat[i, j]);
if (color != -1) {
top[color, j]
= Math.Min(top[color, j], i);
bottom[color, j]
= Math.Max(bottom[color, j], i);
}
}
}
return findarea(mat, R, C, top, bottom, left,
right);
}
// Driven Program
public static void Main(string[] args)
{
char[, ] mat = new char[, ] {
{ 'r', 'r', 'r', 'r', 'r' },
{ 'r', 'r', 'r', 'r', 'g' },
{ 'r', 'r', 'r', 'r', 'r' },
{ 'b', 'b', 'b', 'b', 'b' },
};
Console.WriteLine(maxarea(mat, R, C));
}
}