562. Longest Line of Consecutive One in Matrix

标签:class   return   element   out   line   rect   expand   grid   tco   

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
    }
}

 

562. Longest Line of Consecutive One in Matrix

标签:class   return   element   out   line   rect   expand   grid   tco   

原文地址:https://www.cnblogs.com/johnnyzhao/p/14174974.html

版权声明:完美者 发表于 2020-12-28 11:58:19。
转载请注明:562. Longest Line of Consecutive One in Matrix | 完美导航

暂无评论

暂无评论...