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.
Example:
Input: [[0,1,1,0], [0,1,1,0], [0,0,0,1]] Output: 3
Hint: The number of elements in the given matrix will not exceed 10,000.
思路:dp,用三维矩阵去记录n,m , 4,四个方向的状态,0 row, 1 col, 2 diagonal, 3 anti-diagonal; 如果A[i][j] == 0 ,跳过,为1,则首先赋值四个方向的状态为1,因为周边的点会用到这个点的值。然后四个方向分别dp +1;求个全局的最大;
class Solution {
public int longestLine(int[][] M) {
if(M == null || M.length == 0 || M[0].length == 0) {
return 0;
}
int n = M.length;
int m = M[0].length;
int[][][] dp = new int[n][m][4];
// 0 row, 1 col, 2 diagonal, 3 anti-diagonal;
int res = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(M[i][j] == 0) {
continue;
} else {
// M[i][j] == 1;
// 这个不要忘记,四个维度都为1,跟它相邻的点会用到这四个维度的值;
for(int k = 0; k < 4; k++) {
dp[i][j][k] = 1;
}
// row;
if(j - 1 >= 0) {
dp[i][j][0] = dp[i][j-1][0] + 1;
}
// col;
if(i - 1 >= 0) {
dp[i][j][1] = dp[i - 1][j][1] + 1;
}
// diagonal;
if(i - 1 >= 0 && j + 1 < m) {
dp[i][j][2] = dp[i - 1][j + 1][2] + 1;
}
// anti-diagonal;
if(i - 1 >= 0 && j - 1 >= 0) {
dp[i][j][3] = dp[i - 1][j - 1][3] + 1;
}
res = Math.max(res, Math.max(dp[i][j][0], dp[i][j][1]));
res = Math.max(res, Math.max(dp[i][j][2], dp[i][j][3]));
}
}
}
return res;
}
}