Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created November 26, 2020 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/ddecf29b33eeac11a9501862ce1295f4 to your computer and use it in GitHub Desktop.
Save jianminchen/ddecf29b33eeac11a9501862ce1295f4 to your computer and use it in GitHub Desktop.
maximum line in matrix - Nov. 25, 2020
public int LongestLine(int[][] M) {
if(M == null || M.Length == 0 || M[0].Length == 0)
{
return 0;
}
var rows = M.Length;
var columns = M[0].Length;
var dpH = new int[rows][];
var dpV = new int[rows][];
var dpD = new int[rows][];
for(var row = 0; row < rows; row++)
{
dpH[row] = new int[columns];
dpV[row] = new int[columns];
dpD[row] = new int[columns];
}
var max = 0;
for(int row = 0; row < rows; row++)
{
for(int col = 0; col < columns; col++)
{
var current = M[row][col];
var isOne = current == 1;
if(isOne)
{
dpH[row][col] = 1 + (col > 0? dpH[row][col - 1] : 0);
dpV[row][col] = 1 + (row > 0? dpV[row - 1][col] : 0);
dpD[row][col] = 1 + ((col > 0 && row > 0)? dpD[row - 1][col - 1] : 0);
var array = new int[]{ dpH[row][col], dpV[row][col], dpD[row][col]};
max = Math.Max(max, array.Max());
}
}
}
return max;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment