zoukankan      html  css  js  c++  java
  • 562. Longest Line of Consecutive One in Matrix

    package LeetCode_562
    
    /**
     * 562. Longest Line of Consecutive One in Matrix
     * (Prime)
     *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.
     * */
    class Solution {
        /*
        * solution: scan horizontal,vertical,diagonal, anti-diagonal for each node and calculate current consecutive one,
        * Time:O(m^2 * n^2), Space:O(1)
        * */
        fun longestLine(grid: Array<IntArray>): Int {
            if (grid == null || grid.isEmpty()) {
                return 0
            }
            val m = grid.size
            val n = grid[0].size
            var max = 0
            val directions = arrayOf(
                intArrayOf(1,0),//horizontal
                intArrayOf(0,1),//vertical
                intArrayOf(-1,1),//diagonal
                intArrayOf(-1,-1)//anti-diagonal
            )
            for (i in 0 until m) {
                for (j in 0 until n) {
                    //expand current position where was 1
                    if (grid[i][j] == 0) {
                        continue
                    }
                    for (d in 0 until 4) {
                        var cur = 0
                        var x = i
                        var y = j
                        while (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) {
                            x += directions[d][0]
                            y += directions[d][1]
                            cur++
                        }
                        max = Math.max(cur, max)
                    }
                }
            }
            return max
        }
    }
  • 相关阅读:
    [紫书] 八数码问题(BFS)
    [紫书] 移动盒子(Boxes in a Line)
    [洛谷] P1803 凌乱的yyy / 线段覆盖 (贪心)
    [紫书] 破损的键盘(Broken Keyboard)
    bzoj3891
    poj3233
    bzoj1941
    Vijos2034
    poj2985
    Vijos1100
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/14174974.html
Copyright © 2011-2022 走看看