leetcode562- Longest Line of Consecutive One in Matrix- medium

Posted jasminemzy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode562- Longest Line of Consecutive One in Matrix- medium相关的知识,希望对你有一定的参考价值。

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

Hint: The number of elements in the given matrix will not exceed 10,000.

 

算法:DP,就可以只遍历一遍了。dp[4][row][col]做DP。maxL[4]辅助打擂台。

遍历各个坐标点,记录各个坐标位置开始向左向上向左上向右上分别连续出去能延伸多长。记录下来后打一个擂台。记录方法是,

1.如果前一个依赖点出界,就依当前内容物来。

2.如果前一个依赖点在,而且当前内容物是1,那就可以续上前面的。

3.如果前一个依赖点在,但当前内容物是0,那就清空,续不上了。

全遍历后最后大打擂台,从四强种决一胜负

 

实现:

class Solution {
    public int longestLine(int[][] M) {
        if (M == null || M.length == 0 || M[0].length == 0) {
            return 0;
        }
        int[][][] dp = new int[4][M.length][M[0].length];
        int[] maxL = new int[4];
        int[] dx = {0, -1, -1, -1};
        int[] dy = {-1, 0, -1, +1};
        for (int x = 0; x < M.length; x++) {
            for (int y = 0; y < M[0].length; y++) {
                for (int i = 0; i < 4; i++) {
                    int lastX = x + dx[i];
                    int lastY = y + dy[i];
                    if (!isInBound(M, lastX, lastY)) {
                        dp[i][x][y] = M[x][y];
                    } else if (M[x][y] == 0) {
                        dp[i][x][y] = 0;
                    } else {
                        dp[i][x][y] = dp[i][lastX][lastY] + 1;
                    }
                    maxL[i] = Math.max(maxL[i], dp[i][x][y]);
                }
            }
        }
        
        int result = 0;
        for (int i = 0; i < 4; i++) {
            result = Math.max(result, maxL[i]);
        }
        
        return result;
    }
    
    private boolean isInBound(int[][] M, int x, int y) {
        return x >= 0 && x < M.length && y >= 0 && y < M[0].length;
    }
}

 

以上是关于leetcode562- Longest Line of Consecutive One in Matrix- medium的主要内容,如果未能解决你的问题,请参考以下文章

562. Longest Line of Consecutive One in Matrix

562. Longest Line of Consecutive One in Matrix

[LeetCode] Longest Line of Consecutive One in Matrix 矩阵中最长的连续1

3 Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

LeetCode Longest Palindrome