public int longestLine(int[][] M) {
if (M == null || M.length == 0) {
int m = M.length, n = M[0].length;
// dp[i][j][0] means the longest consecutive 1 horizontally at (i, j)
// dp[i][j][1] means the longest consecutive 1 vertically at (i, j)
// dp[i][j][2] means the longest consecutive 1 diagnolly at (i, j)
// dp[i][j][3] means the longest consecutive 1 anti-diagnolly (i, j)
int[][][] dp = new int[m][n][4];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1;
dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1;
dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1;
dp[i][j][3] = (i > 0 && j < n - 1) ? dp[i - 1][j + 1][3] + 1 : 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]));