首页 > 其他 > 详细

562. Longest Line of Consecutive One in Matrix

时间:2018-11-08 17:51:18      阅读:168      评论:0      收藏:0      [点我收藏+]
https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/solution/


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




class Solution {
    public int longestLine(int[][] M) {
        int res = 0;
        if(M == null || M.length == 0) return res;
        int m = M.length;
        int n = M[0].length;
        int[][][] dp = new int[m][n][4];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(M[i][j] == 1){
                    // horizontal 
                    dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1;
                    // vertical
                    dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1;
                    // diag
                    dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1;
                    // rever dia
                    dp[i][j][3] = (i > 0 && j + 1 < n) ? dp[i - 1][j + 1][3] + 1 : 1; // j + 1 < n 
                    res = Math.max(res, Math.max(Math.max(dp[i][j][0], dp[i][j][1]), Math.max(dp[i][j][2], dp[i][j][3])));
                }
            }
        }
        return res;  
    }
}

 

562. Longest Line of Consecutive One in Matrix

原文:https://www.cnblogs.com/tobeabetterpig/p/9929933.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!