-
Notifications
You must be signed in to change notification settings - Fork 154
/
longest-line-of-consecutive-one-in-matrix.js
54 lines (47 loc) · 1.17 KB
/
longest-line-of-consecutive-one-in-matrix.js
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
/**
* Longest Line of Consecutive One in Matrix
*
* 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.
*/
/**
* @param {number[][]} M
* @return {number}
*/
const longestLine = M => {
if (M.length === 0) {
return 0;
}
const m = M.length;
const n = M[0].length;
const dp = [];
for (let i = 0; i < 4; i++) {
dp[i] = Array(m)
.fill()
.map(() => Array(n).fill(0));
}
let ones = 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (M[i][j] === 1) {
dp[0][i][j] = j > 0 ? dp[0][i][j - 1] + 1 : 1;
dp[1][i][j] = i > 0 ? dp[1][i - 1][j] + 1 : 1;
dp[2][i][j] = i > 0 && j > 0 ? dp[2][i - 1][j - 1] + 1 : 1;
dp[3][i][j] = i > 0 && j < n - 1 ? dp[3][i - 1][j + 1] + 1 : 1;
ones = Math.max(ones, Math.max(Math.max(dp[0][i][j], dp[1][i][j]), Math.max(dp[2][i][j], dp[3][i][j])));
}
}
}
return ones;
};
export { longestLine };