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.

Solution

class Solution {
    public int longestLine(int[][] M) {
        if (M == null || M.length == 0 || M[0].length == 0) return 0;
        int max = 0, m = M.length, n = M[0].length;
        int[] row = new int[m];
        int[] col = new int[n];
        int[] d = new int[m+n];
        int[] ad = new int[m+n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (M[i][j] == 1) {
                    row[i]++;
                    col[j]++;
                    d[i+j]++;
                    ad[j-i+m]++;
                    max = Math.max(max, Math.max(row[i], col[j]));
                    max = Math.max(max, Math.max(d[i+j], ad[j-i+m]));
                } else {
                    row[i] = 0;
                    col[j] = 0;
                    d[i+j] = 0;
                    ad[j-i+m] = 0;
                }
            }
        }
        return max;
    }
}

linspiration
161 声望53 粉丝