Given a 01 matrix, find the longest line of consecutive 1 in the matrix. The line could be horizontal, vertical, diagonal or anti-diagonal.

Example 1:

Input:
[[0,1,1,0],
[0,1,1,0],
[0,0,0,1]]
Output: 3
Explanation: (0,1) (1,2) (2,3)

Example 2:

Input: [[0,0],[1,1]]
Output: 2
https://www.cnblogs.com/grandyang/p/6900866.html
我们也可以考虑用DP解法来做,我们建立一个三维dp数组,其中dp[i][j][k]表示从开头遍历到数字nums[i][j]为止,第k种情况的连续1的个数,k的值为0,1,2,3,
分别对应水平,竖直,对角线和逆对角线这四种情况。之后就是更新dp数组的过程了,如果如果数字为0的情况直接跳过,然后水平方向就加上前一个的dp值,竖直方向加上上面
一个数字的dp值,对角线方向就加上右上方数字的dp值,逆对角线就加上左上方数字的dp值,然后每个值都用来更新结果res,参见代码如下:
 class Solution2 {
int longestLine(int[][] M) {
if (M == null || M.length == || M[].length == ) return ;
int m = M.length, n = M[].length, res = ;
int[][][] dp = new int[m][n][];
for (int i = ; i < m; ++i) {
for (int j = ; j < n; ++j) {
if (M[i][j] == ) continue;
for (int k = ; k < ; ++k) dp[i][j][k] = ;
if (j > ) dp[i][j][] += dp[i][j - ][]; // horizonal
if (i > ) dp[i][j][] += dp[i - ][j][]; // vertical
if (i > && j < n - ) dp[i][j][] += dp[i - ][j + ][]; // diagonal
if (i > && j > ) dp[i][j][] += dp[i - ][j - ][]; // anti-diagonal
res = Math.max(res, Math.max(dp[i][j][], dp[i][j][]));
res = Math.max(res, Math.max(dp[i][j][], dp[i][j][]));
}
}
return res;
}
}
05-11 22:21