一次AC,87.60%的速度。注意算右上左下对角线,开dig2[m+1][n+2]; 只依赖于上一层,可以通过滚动数组优化到space O(m+n)
public class Solution {
public int longestLine(int[][] M) {
if(M==null || M.length==0) return 0;
int m = M.length; int n = M[0].length;
int[][] row = new int[m+1][n+1]; int[][] col = new int[m+1][n+1];
int[][] dig1 = new int[m+1][n+1]; int[][] dig2 = new int[m+1][n+2]; int ans =0;
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++){
if(M[i-1][j-1]==0){
row[i][j]=0; col[i][j]=0;
dig1[i][j]=0; dig2[i][j]=0;
}
else{
row[i][j] = row[i][j-1]+1;
col[i][j] = col[i-1][j]+1;
dig1[i][j] = dig1[i-1][j-1]+1;
dig2[i][j] = dig2[i-1][j+1]+1;
ans = Math.max(ans, row[i][j]);
ans = Math.max(ans, col[i][j]);
ans = Math.max(ans, dig1[i][j]);
ans = Math.max(ans, dig2[i][j]);
}
}
return ans;
}
}