给定一个01矩阵m
,找出矩阵中连续的最长的直线。这条线可以是水平的,垂直的,对角线的或者反对角线的。
样例
给定 m =
[
[0,1,1,0],
[0,1,1,0],
[0,0,0,1]
]
返回 3
注意事项
给定矩阵中的元素个数不超过10000
。
思路:看到题的时候想到了最笨的方法,但是感觉不应该这么做。所以找到了别人的做法,利用动态规划做的,
虽然我也不是很清楚动态规划的原理,但是代码是看懂了的,这里就写一下我的理解就好了
public class Solution {
/**
* @param M: the 01 matrix
* @return: the longest line of consecutive one in the matrix
*/
public int longestLine(int[][] M) {
// Write your code here
if(M.length==0||M==null){
return 0;
}
int rows = M.length;
int cols = M[0].length;
int [][][] dp = new int[rows][cols][4];//创建一个三维的动态规划数组,相当于给每个1出现的位置标记为1
int count=0;
for (int i =0;i<rows;i++){
for(int j =0;j<cols;j++){
if(M[i][j]==0)continue;//如果是0则跳过
for(int k =0;k<4;k++){
dp[i][j][k]=1;否则将行、列、对角、反对角的位置都标记为1
}
if(j>0){
dp[i][j][0]+=dp[i][j-1][0];
}
if(i>0){
dp[i][j][1]+=dp[i-1][j][1];
}
if(i>0&&j>0){
dp[i][j][2]+=dp[i-1][j-1][2];
}
if(i>0&&j<cols-1){
dp[i][j][3]+=dp[i-1][j+1][3];
}
count = Math.max(count,Math.max(dp[i][j][0],dp[i][j][1]));
count = Math.max(count,Math.max(dp[i][j][2],dp[i][j][3]));
}
}
return count;
}
}