-
Notifications
You must be signed in to change notification settings - Fork 2
/
2D Hopscotch.cpp
62 lines (61 loc) · 2.7 KB
/
2D Hopscotch.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
class Solution{
public:
bool valid(int i, int j, int n, int m) {
if(i >= 0 && j >= 0 && i < n && j < m)
return true;
return false;
}
int hopscotch(int n, int m, vector<vector<int>> mat, int ty, int i, int j)
{
int sum = 0;
if(ty == 0) {
if(j%2 == 0) {
if(valid(i-1, j-1, n, m)) sum += mat[i-1][j-1];
if(valid(i-1, j, n, m)) sum += mat[i-1][j];
if(valid(i-1, j+1, n, m)) sum += mat[i-1][j+1];
if(valid(i, j-1, n, m)) sum += mat[i][j-1];
if(valid(i, j+1, n, m)) sum += mat[i][j+1];
if(valid(i+1, j, n, m)) sum += mat[i+1][j];
}
else{
if(valid(i-1, j, n, m)) sum += mat[i-1][j];
if(valid(i, j-1, n, m)) sum += mat[i][j-1];
if(valid(i, j+1, n, m)) sum += mat[i][j+1];
if(valid(i+1, j-1, n, m)) sum += mat[i+1][j-1];
if(valid(i+1, j, n, m)) sum += mat[i+1][j];
if(valid(i+1, j+1, n, m)) sum += mat[i+1][j+1];
}
}
else{
if(j%2 == 0) {
if(valid(i-2, j-1, n, m)) sum += mat[i-2][j-1];
if(valid(i-2, j, n, m)) sum += mat[i-2][j];
if(valid(i-2, j+1, n, m)) sum += mat[i-2][j+1];
if(valid(i-1, j-2, n, m)) sum += mat[i-1][j-2];
if(valid(i-1, j+2, n, m)) sum += mat[i-1][j+2];
if(valid(i, j-2, n, m)) sum += mat[i][j-2];
if(valid(i, j+2, n, m)) sum += mat[i][j+2];
if(valid(i+1, j-2, n, m)) sum += mat[i+1][j-2];
if(valid(i+1, j-1, n, m)) sum += mat[i+1][j-1];
if(valid(i+1, j+1, n, m)) sum += mat[i+1][j+1];
if(valid(i+1, j+2, n, m)) sum += mat[i+1][j+2];
if(valid(i+2, j, n, m)) sum += mat[i+2][j];
}
else{
if(valid(i-1, j-2, n, m)) sum += mat[i-1][j-2];
if(valid(i-1, j-1, n, m)) sum += mat[i-1][j-1];
if(valid(i-2, j, n, m)) sum += mat[i-2][j];
if(valid(i-1, j+1, n, m)) sum += mat[i-1][j+1];
if(valid(i-1, j+2, n, m)) sum += mat[i-1][j+2];
if(valid(i, j-2, n, m)) sum += mat[i][j-2];
if(valid(i, j+2, n, m)) sum += mat[i][j+2];
if(valid(i+1, j-2, n, m)) sum += mat[i+1][j-2];
if(valid(i+1, j+2, n, m)) sum += mat[i+1][j+2];
if(valid(i+2, j-1, n, m)) sum += mat[i+2][j-1];
if(valid(i+2, j, n, m)) sum += mat[i+2][j];
if(valid(i+2, j+1 ,n, m)) sum += mat[i+2][j+1];
}
}
return sum;
}
};