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.
递归的解法,同时maintain一个最大值,注意8个方向中只需要走4个方向即可。
public class Solution {
int [][] directions = new int[][]{{1,0},{0,1},{1,1},{1,-1}};
public int longestLine(int[][] M) {
if(M == null || M.length == 0 || M[0].length == 0) return 0;
int res = 0;
for(int i =0; i < M.length; i++){
for(int j = 0;j < M[0].length; j++){
if(M[i][j] == 1){
res = Math.max(res,getMax(M, i, j));
}
}
}
return res;
}
private int getMax(int [][] M, int x, int y){
int res = 1;
for(int [] dir : directions){
int i = x + dir[0];
int j = y + dir[1];
int count = 1;
while(i< M.length && j< M[0].length && i >= 0 && j >= 0 && M[i][j] == 1){
i += dir[0];
j += dir[1];
count++;
}
res = Math.max(count,res);
}
return res;
}
}