题目: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.
思路:题目的意思就是求一个给定二维矩阵上在水平方向、垂直方向、对角线方向和反对角线方向上连续1的最大个数。
可以采用动态规划的方法解决这题。建立一个三维的dp矩阵,其中dp[i][j][k]表示从开头遍历到数字M[i][j]为止,第k种情况的连续1的个数,k的值分别为0,1,2,3分别对应水平、垂直、对角线和反对角线四种情况。之后就是更新dp的过程,如果数字为0的情况就直接跳过,然后,水平方向就加上左边一个的dp值,垂直方向加上上边一个的dp值,对角线方向就加上右上的dp值,反对角线就加上左上的dp值,每个值都用来更新count。
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==null||M.length==0) return 0;
int rows=M.length;
int cols=M[0].length;
int [][][] dp=new int[rows][cols][4];
int count=0;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(M[i][j]==0) continue;
for(int k=0;k<4;k++) dp[i][j][k]=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;
}
}