المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Submatrix problem



C# Programming
03-28-2009, 05:12 AM
Hello everyone, I have to find the biggest rectangle(square) in a matrix which holds only even numbers.
If I have normal rectangle with even numbers my code is working, but if I have some strange figure like two rectangles in one my code fails.
Please anyone who have done something similar before to give me a clue how to get this rectangle.
I am not very sure is it my post for here, so if its not please excuse me.
Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EvenNumberMatrix
{
class EvenNumbers
{
//Exaple of working array
/*public static int[,] givenArray ={
{5,2,6,8,5,9},
{7,5,3,2,4,7},
{9,6,3,6,4,3},
{8,5,3,6,2,2},
{9,6,3,7,4,7},
{8,5,6,2,2,5}
};
*/
//Not working array
public static int[,] givenArray ={
{5,2,6,8,5,9},
{7,5,3,2,4,7},
{9,6,3,6,4,2},
{8,5,3,6,2,2},
{9,6,3,7,4,7},
{8,5,6,2,2,5}
};
public static int maxCol = 0, maxRow = 0;
//temp array to make all odd numbers zeros
public static int[,] tempGivenArray;
static void PrintArray(int[,] a)
{
for (int x = 0; x < a.GetLength(0); x++)
{
for (int y = 0; y < a.GetLength(1); y++)
{
if (a[x, y] != 0)
{
Console.ForegroundColor = ConsoleColor.Green;
}
else
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(a[x, y] + " ");
}
Console.WriteLine();
}
}

static void Main(string[] args)
{
int number = 6; int countRows = 0, countCollums = 0, x, y;

tempGivenArray = new int[number, number];
// zapisvam 4etnite 4isla v nov masiv samo s nuli
for (int i = 0; i < number - 1; i++)
{
for (int j = 0; j < number - 1; j++)
{
if (givenArray[i, j] % 2 == 0 &&
givenArray[i + 1, j] % 2 == 0 &&
givenArray[i, j + 1] % 2 == 0 &&
givenArray[i + 1, j + 1] % 2 == 0)
{
tempGivenArray[i, j] = givenArray[i, j];
tempGivenArray[i + 1, j] = givenArray[i + 1, j];
tempGivenArray[i, j + 1] = givenArray[i, j + 1];
tempGivenArray[i + 1, j + 1] = givenArray[i + 1, j + 1];
}
}
}
for (int i = 0; i < number - 1; i++)
{
for (int j = 0; j < number - 1; j++)
{
x = i; y = j;
//loop to check if in a current row even numbers
while (tempGivenArray[x, y] > 0)
{
x++;
countRows++;
if (countRows > maxRow)
maxRow = countRows;//maxRow holds positions for even number in row
if (x > number - 1)//if out of array
break;
}
x = i; y = j; countRows = 0;
while (tempGivenArray[x, y] > 0)
{
y++;
countCollums++;
if (countCollums > maxCol)//maxCol holds positions for even number in collum
maxCol = countCollums;
if (y > number - 1)//if out of array
break;
}
countCollums = 0;

}
}
PrintArray(tempGivenArray);
Console.WriteLine("The biggest rectangle with even numbers is: "+maxCol * maxRow+" positions!");

}

}
}

Thank you very much in advance