-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathLongestLineOfOnes.cpp
74 lines (66 loc) · 1.43 KB
/
LongestLineOfOnes.cpp
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
// Problem: https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/
#include <vector>
using namespace std;
class LongestLineOfOnes {
public:
int longestLine(vector<vector<int>>& mat) {
int max_rows = mat.size();
int max_cols = mat[0].size();
int max_ones = 0;
// Case-I: Iterate horizontally.
for (int r = 0; r < max_rows; ++r) {
int ones = 0;
for (int c = 0; c < max_cols; ++c) {
if (mat[r][c] == 1) {
++ones;
max_ones = max(max_ones, ones);
}
else ones = 0;
}
}
// Case-II: Iterate vertically.
for (int c = 0; c < max_cols; ++c) {
int ones = 0;
for (int r = 0; r < max_rows; ++r) {
if (mat[r][c] == 1) {
++ones;
max_ones = max(max_ones, ones);
}
else ones = 0;
}
}
// Case-III: Iterate diagonally
for (int r = 0; r < max_rows; ++r) {
for (int c = 0; c < max_cols; ++c) {
int ones = 0;
int x = r, y = c;
while (x < max_rows && y < max_cols) {
if (mat[x][y] == 1) {
++ones;
max_ones = max(max_ones, ones);
}
else ones = 0;
++x;
++y;
}
}
}
// Case-IV: Iterate anti-diagonally
for (int r = 0; r < max_rows; ++r) {
for (int c = 0; c < max_cols; ++c) {
int ones = 0;
int x = r, y = c;
while (x < max_rows && y >= 0) {
if (mat[x][y] == 1) {
++ones;
max_ones = max(max_ones, ones);
}
else ones = 0;
++x;
--y;
}
}
}
return max_ones;
}
};