Count Fertile Pyramids in a Land LeetCode solution in Java

1
class Solution {
2
public int countPyramids(int[][] grid) {
3
int m = grid.length, n = grid[0].length;
4
int[][] rev = new int[m][n];
5
for (int i = 0; i < m; ++i) {
6
for (int j = 0; j < n; ++j) rev[m - i - 1][j] = grid[i][j];
7
}
8
return cal(grid) + cal(rev);
9
}
10

11
private int cal(int[][] grid) {
12
int m = grid.length, n = grid[0].length, res = 0;
13
for (int i = 1; i < m; ++i) {
14
for (int j = 0, cnt = 0; j < n; ++j) {
15
if (0 != grid[i][j]) cnt++;
16
else cnt = 0;
17
if (0 == cnt || 0 == j) continue;
18
grid[i][j] = Math.min(grid[i - 1][j - 1] + 1, (cnt + 1) >> 1);
19
res += grid[i][j] - 1;
20
}
21
}
22
return res;
23
}
24
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0