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

562. Longest Line of Consecutive One in Matrix

时间:2020-12-28 11:58:19      阅读:0      评论:0      收藏:0      [点我收藏+]

标签: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

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