forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2013-Detect-Squares.java
110 lines (101 loc) · 3.25 KB
/
2013-Detect-Squares.java
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// https://leetcode.com/submissions/detail/761120641/
class DetectSquares {
private Integer[][] matrix;
public DetectSquares() {
matrix = new Integer[1001][1001];
}
public void add(int[] point) {
if (matrix[point[0]][point[1]] == null) {
matrix[point[0]][point[1]] = 1;
} else {
matrix[point[0]][point[1]] = matrix[point[0]][point[1]] + 1;
}
}
public int count(int[] point) {
int currentSquareCount = 0;
int currentPointCount = 1;
int startRow = point[0];
int startCol = point[1];
int curRow = point[0];
int curCol = point[1];
while (curRow != 0 && curCol != 0) {
curRow--;
curCol--;
if (
matrix[curRow][curCol] != null &&
matrix[startRow][curCol] != null &&
matrix[curRow][startCol] != null
) {
currentSquareCount =
currentSquareCount +
(
currentPointCount *
matrix[curRow][curCol] *
matrix[startRow][curCol] *
matrix[curRow][startCol]
);
}
}
curRow = point[0];
curCol = point[1];
while (curRow != 1000 && curCol != 1000) {
curRow++;
curCol++;
if (
matrix[curRow][curCol] != null &&
matrix[startRow][curCol] != null &&
matrix[curRow][startCol] != null
) {
currentSquareCount =
currentSquareCount +
(
currentPointCount *
matrix[curRow][curCol] *
matrix[startRow][curCol] *
matrix[curRow][startCol]
);
}
}
curRow = point[0];
curCol = point[1];
while (curRow != 0 && curCol != 1000) {
curRow--;
curCol++;
if (
matrix[curRow][curCol] != null &&
matrix[startRow][curCol] != null &&
matrix[curRow][startCol] != null
) {
currentSquareCount =
currentSquareCount +
(
currentPointCount *
matrix[curRow][curCol] *
matrix[startRow][curCol] *
matrix[curRow][startCol]
);
}
}
curRow = point[0];
curCol = point[1];
while (curRow != 1000 && curCol != 0) {
curRow++;
curCol--;
if (
matrix[curRow][curCol] != null &&
matrix[startRow][curCol] != null &&
matrix[curRow][startCol] != null
) {
currentSquareCount =
currentSquareCount +
(
currentPointCount *
matrix[curRow][curCol] *
matrix[startRow][curCol] *
matrix[curRow][startCol]
);
}
}
return currentSquareCount;
}
}