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
Solution:
思路:
DP解法
dp[i][j][k]表示从开头遍历到数字nums[i][j]为止,第k种情况的连续1的个数.
k的值为0,1,2,3,分别对应水平,竖直,对角线和逆对角线这四种情况。
更新dp数组过程:
如果如果数字为0的情况直接跳过,然后水平方向就加上前一个的dp值,竖直方向加上上面一个数字的dp值,对角线方向就加上右上方数字的dp值,逆对角线就加上左上方数字的dp值,然后每个值都用来更新结果res.
Time Complexity: O(mn) Space Complexity: O(mn)
Solution Code:
class Solution {
public int longestLine(int[][] M) {
int n = M.length, max = 0;
if (n == 0) return max;
int m = M[0].length;
int[][][] dp = new int[n][m][4];
for (int i=0;i<n;i++)
for (int j=0;j<m;j++) {
if (M[i][j] == 0) continue;
for (int k = 0;k < 4;k++) dp[i][j][k] = 1;
if (j > 0) dp[i][j][0] += dp[i][j-1][0]; // horizontal line
if (j > 0 && i > 0) dp[i][j][1] += dp[i-1][j-1][1]; // anti-diagonal line
if (i > 0) dp[i][j][2] += dp[i-1][j][2]; // vertical line
if (j < m-1 && i > 0) dp[i][j][3] += dp[i-1][j+1][3]; // diagonal line
max = Math.max(max, Math.max(dp[i][j][0], dp[i][j][1]));
max = Math.max(max, Math.max(dp[i][j][2], dp[i][j][3]));
}
return max;
}
}
网友评论