-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path562-LongestLineOfConsecutiveOneInMatrix.go
More file actions
74 lines (67 loc) · 2.08 KB
/
562-LongestLineOfConsecutiveOneInMatrix.go
File metadata and controls
74 lines (67 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
// 562. Longest Line of Consecutive One in Matrix
// Given an m x n binary matrix mat, return the length of the longest line of consecutive one in the matrix.
// The line could be horizontal, vertical, diagonal, or anti-diagonal.
// Example 1:
// <img src="https://assets.leetcode.com/uploads/2021/04/24/long1-grid.jpg" />
// Input: mat = [[0,1,1,0],[0,1,1,0],[0,0,0,1]]
// Output: 3
// Example 2:
// <img src="https://assets.leetcode.com/uploads/2021/04/24/long2-grid.jpg" />
// Input: mat = [[1,1,1,1],[0,1,1,0],[0,0,0,1]]
// Output: 4
// Constraints:
// m == mat.length
// n == mat[i].length
// 1 <= m, n <= 10^4
// 1 <= m * n <= 10^4
// mat[i][j] is either 0 or 1.
import "fmt"
func longestLine(mat [][]int) int {
m, n, res := len(mat), len(mat[0]), 0
dp := make([][][4]int, m + 1)
for i := range dp {
dp[i] = make([][4]int, n+1)
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
if mat[i-1][j-1] == 1 {
dp[i][j][0] = dp[i][j-1][0] + 1 // 水平
dp[i][j][1] = dp[i-1][j][1] + 1 // 垂直
dp[i][j][2] = dp[i-1][j-1][2] + 1 // 对角线
dp[i][j][3] = 1 // 反对角线
if j + 1 <= n {
dp[i][j][3] += dp[i-1][j+1][3]
}
for _, v := range dp[i][j] {
if v > res {
res = v
}
}
}
}
}
return res
}
func main() {
// Example 1:
// <img src="https://assets.leetcode.com/uploads/2021/04/24/long1-grid.jpg" />
// Input: mat = [[0,1,1,0],[0,1,1,0],[0,0,0,1]]
// Output: 3
mat1 := [][]int{
{0,1,1,0},
{0,1,1,0},
{0,0,0,1},
}
fmt.Println(longestLine(mat1)) // 3
// Example 2:
// <img src="https://assets.leetcode.com/uploads/2021/04/24/long2-grid.jpg" />
// Input: mat = [[1,1,1,1],[0,1,1,0],[0,0,0,1]]
// Output: 4
mat2 := [][]int{
{1,1,1,1},
{0,1,1,0},
{0,0,0,1},
}
fmt.Println(longestLine(mat2)) // 4
}