562 Longest Line of Consecutive One in Matrix

1. Question

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.

2. Implementation

(1) DP

public class Solution {
    public int longestLine(int[][] M) {
        if (M == null || M.length == 0) {
            return 0;
        }

        int m = M.length, n = M[0].length;
        int res = 0;

        // 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++) {
                if (M[i][j] == 1) {
                    // Horizontal
                    dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1;
                    // Vertical
                    dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1;
                    // Diagnol
                    dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1;
                    // Anti-Diagnol
                    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]));
                }
            }
        }
        return res;
    }
}

3. Time & Space Complexity

DP: 时间复杂度O(mn), 空间复杂度O(mn)

Last updated