Last active
February 26, 2019 07:24
-
-
Save imgen/d0c653222afd5339efe1929c07b7d670 to your computer and use it in GitHub Desktop.
Calculate max rectangle area of a matrix of 0 and 1s
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public class Program { | |
public static void Main() { | |
var matrices = new []{ | |
new [] { | |
"00000", | |
"00000", | |
"00000", | |
"00000", | |
"00000" | |
}, | |
new [] { | |
"10000", | |
"00000", | |
"10000", | |
"10000", | |
"00000" | |
}, | |
new [] { | |
"11011", | |
"01101", | |
"11110", | |
"11111", | |
"01111" | |
}, | |
new [] { | |
"101101", | |
"111111", | |
"011111", | |
"111111", | |
"001111", | |
"011111" | |
} | |
}; | |
foreach(var matrix in matrices) { | |
int maxArea = CalculateMaxRectangleArea(matrix); | |
Console.WriteLine($"The max rectangle area is {maxArea}"); | |
} | |
} | |
static int CalculateMaxRectangleArea(string[] matrix) { | |
int maxArea = 0, loopCounter = 0; | |
for (int i = 0; i < matrix.Length; i++) { | |
for (int j = 0; j < matrix[i].Length; j++) { | |
int maxVerticalExtend = matrix.Length - i; | |
for (int horizontalExtend = 0; j + horizontalExtend < matrix[i].Length; horizontalExtend++) { | |
int verticalExtend = 0; | |
for (; verticalExtend < maxVerticalExtend; verticalExtend++) { | |
loopCounter++; | |
if (matrix[i + verticalExtend][j + horizontalExtend] == '0') // Not every cell is 1, we break out prematurely | |
break; | |
int area = (horizontalExtend + 1) * (verticalExtend + 1); | |
if (area > maxArea) | |
maxArea = area; | |
} | |
maxVerticalExtend = verticalExtend; | |
} | |
} | |
} | |
Console.WriteLine($"The loop count is {loopCounter}"); | |
return maxArea; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment