# 562 Longest Line of Consecutive One in Matrix

### Problem:

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.

### Solutions:

``````public class Solution {
public int longestLine(int[][] M) {
int res = 0;
if (M == null || M.length == 0 || M.length == 0) {
return 0;
}
int m = M.length, n = M.length;
int[][][] dp = new int[m][n];
// dp[x][y] is for horizontal
// dp[x][y] is for vertical
// dp[x][y] is for diagonal
// dp[x][y] is for anti-diagonal
dp = dp = dp = dp= M;
res = Math.max(res, M);
for (int i = 0; i < m; i ++) {
for (int j = 0; j < n; j ++) {
if (M[i][j] == 1) {
dp[i][j] = dp[i][j] = dp[i][j] = dp[i][j] = 1;
if (j > 0) {
dp[i][j] = dp[i][j - 1] + 1;
}
if (i > 0) {
dp[i][j] = dp[i - 1][j] + 1;
}
if (i > 0 && j > 0) {
dp[i][j] = dp[i - 1][j - 1] + 1;
}
if (j + 1 < n && i > 0) {
dp[i][j] = dp[i - 1][j + 1] + 1;
}
res = Math.max(res, dp[i][j]);
res = Math.max(res, dp[i][j]);
res = Math.max(res, dp[i][j]);
res = Math.max(res, dp[i][j]);
}
}
}
return res;
}
}
``````