Last active
November 7, 2017 10:13
-
-
Save BiruLyu/3923151582d3253da218648a90312784 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int longestLine(int[][] M) { | |
if (M == null || M.length < 1 || M[0].length < 1) return 0; | |
int m = M.length; | |
int n = M[0].length; | |
int[][][] dp = new int[m][n][4]; | |
int res = 0; | |
for (int i = 0; i < m; i++) { | |
for (int j = 0; j < n; j++) { | |
if (M[i][j] == 0) continue; | |
for (int k = 0; k < 4; k++) dp[i][j][k] = 1; | |
if (i > 0) dp[i][j][0] += dp[i - 1][j][0]; // vertical line | |
if (j > 0) dp[i][j][1] += dp[i][j - 1][1]; // horizontal | |
if (i > 0 && j > 0) dp[i][j][2] += dp[i - 1][j - 1][2]; // anti-diagonal | |
if (i > 0 && j < n - 1) dp[i][j][3] += dp[i - 1][j + 1][3]; // diagonal | |
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int longestLine(int[][] M) { | |
int l = M.length; | |
if(l==0) | |
return 0; | |
int w = M[0].length; | |
int horizen[] = new int [w]; | |
int ver= 0; | |
int dia [] = new int [l+w-1]; | |
int anti [] = new int [l+w-1]; | |
int result = 0; | |
for(int i=0;i<l;i++){ | |
ver = 0; | |
for(int j=0;j<w;j++){ | |
if(M[i][j]==1){ | |
horizen[j]++; | |
ver++; | |
dia[i+j]++; | |
anti[l-1-(i-j)]++; | |
}else{ | |
result = Math.max(ver, result); | |
ver = 0; | |
result = Math.max(horizen[j], result); | |
horizen[j] = 0; | |
result = Math.max(dia[i+j], result); | |
dia[i+j] = 0; | |
result = Math.max(anti[l-1-(i-j)], result); | |
anti[l-1-(i-j)] = 0; | |
} | |
} | |
if(ver>0){ | |
result = Math.max(ver, result); | |
} | |
} | |
for(int i=0;i<w;i++){ | |
result = Math.max(horizen[i], result); | |
} | |
for(int i=0;i<w+l-1;i++){ | |
result = Math.max(anti[i], result); | |
result = Math.max(dia[i], result); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment