# 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.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]
y += directions[d]
cur++
}
max = Math.max(cur, max)
}
}
}
return max
}
}```

562. Longest Line of Consecutive One in Matrix