zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    MT【55】近零点
    MT【54】一道二次函数问题的几何意义
    MT【53】对数平均做数列放缩
    MT【52】空间法向量理解直线条数
    MT【51】一道三角求最值问题
    MT【50】高中曲线系集大成之双切线法
    MT【49】四次函数求最值
    ps中图层混合模式、多图层叠加、不透明度、填充、图层样式详解
    GDB基本调试
    24位和8位BMP图片保存纯C代码
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7986488.html
Copyright © 2011-2022 走看看