Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be horizontal, vertical, diagonal or anti-diagonal.
/**
* 动态规划解法
* @param matrix
* 01矩阵
* [[0,1,1,0],
* [0,1,1,0],
* [0,0,0,1]]
* @return 返回水平、垂直、对角线中最多的1
*/
public int longestLine(int[][] matrix){
if (matrix == null || matrix.length == 0) return 0;
int rows = matrix.length, cols = matrix[0].length;
int[][][] dp = new int[rows + 1][cols + 2][4]; //动态规划 行+1 列+2 4个方向(水平、垂直、2对角)
int res = 0;
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
if (matrix[i][j] == 1){
dp[i+1][j+1][0] = dp[i+1][j][0] + 1;
res = Math.max(res, dp[i+1][j+1][0]);
dp[i+1][j+1][1] = dp[i][j+1][1] + 1;
res = Math.max(res, dp[i][j+1][1]);
dp[i+1][j+1][2] = dp[i][j][2] + 1;
res = Math.max(res, dp[i][j][2]);
dp[i+1][j+1][3] = dp[i][j+2][3] + 1;
res = Math.max(res, dp[i][j+2][3]);
}
}
}
return res;
}

1373

被折叠的 条评论
为什么被折叠?



