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
1 public class Solution { 2 int[][] directions = new int[][] { { 1, 0 }, { 0, 1 }, { 1, 1 }, { 1, -1 } }; 3 4 public int longestLine(int[][] M) { 5 if (M == null || M.length == 0 || M[0].length == 0) 6 return 0; 7 int res = 0; 8 for (int i = 0; i < M.length; i++) { 9 for (int j = 0; j < M[0].length; j++) { 10 if (M[i][j] == 1) { 11 res = Math.max(res, getMax(M, i, j)); 12 } 13 } 14 } 15 return res; 16 } 17 18 private int getMax(int[][] M, int x, int y) { 19 int res = 1; 20 for (int[] dir : directions) { 21 int i = x + dir[0]; 22 int j = y + dir[1]; 23 int count = 1; 24 while (i < M.length && j < M[0].length && i >= 0 && j >= 0 && M[i][j] == 1) { 25 i += dir[0]; 26 j += dir[1]; 27 count++; 28 } 29 res = Math.max(count, res); 30 } 31 return res; 32 } 33 34 int longestLineV2(int[][] M) { 35 if (M == null || M.length == 0 || M[0].length == 0) return 0; 36 int m = M.length, n = M[0].length, res = 0; 37 int[][] dirs = { { 1, 0 }, { 0, 1 }, { -1, -1 }, { -1, 1 } }; 38 for (int i = 0; i < m; ++i) { 39 for (int j = 0; j < n; ++j) { 40 if (M[i][j] == 0) 41 continue; 42 for (int k = 0; k < 4; ++k) { 43 int cnt = 0, x = i, y = j; 44 while (x >= 0 && x < m && y >= 0 && y < n && M[x][y] == 1) { 45 x += dirs[k][0]; 46 y += dirs[k][1]; 47 ++cnt; 48 } 49 res = Math.max(res, cnt); 50 } 51 } 52 } 53 return res; 54 } 55 }