码迷,mamicode.com
首页 > 其他好文 > 详细

562. Longest Line of Consecutive One in Matrix

时间:2018-11-08 18:32:34      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:line   .com   vertica   com   nta   ica   NPU   int   tput   

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

标签:line   .com   vertica   com   nta   ica   NPU   int   tput   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!