-
Notifications
You must be signed in to change notification settings - Fork 0
/
CharGrid.java
92 lines (84 loc) · 1.96 KB
/
CharGrid.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
// HW1 2-d array Problems
// CharGrid encapsulates a 2-d grid of chars and supports
// a few operations on the grid.
import java.util.HashSet;
public class CharGrid {
private char[][] grid;
/**
* Constructs a new CharGrid with the given grid.
* Does not make a copy.
* @param grid
*/
public CharGrid(char[][] grid) {
this.grid = grid;
}
/**
* Returns the area for the given char in the grid. (see handout).
* @param ch char to look for
* @return area for given char
*/
public int charArea(char ch) {
if (grid.length < 1)
return 0;
int maxX = -1;
int minX = grid.length;
int minY = grid[0].length;
int maxY = -1;
for (int i = 0; i< grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == ch) {
maxX = Math.max(maxX, i);
minX = Math.min(minX, i);
maxY = Math.max(maxY, j);
minY = Math.min(minY, j);
}
}
}
int x = maxX - minX + 1;
int y = maxY - minY + 1;
return maxX!=-1 ? x*y : 0;
}
/**
* Returns the count of '+' figures in the grid (see handout).
* @return number of + in grid
*/
public int countPlus() {
if (grid.length < 1)
return 0;
int height = grid.length;
int width = grid[0].length;
int res = 0;
for (int i=0; i<height; i++) {
for (int j = 0; j<width; j++) {
res += isPlusCenter (i, j);
}
}
return res;
}
private int isPlusCenter(int n, int m) {
HashSet<Integer> sizes = new HashSet<Integer>();
for (int i=-1; i<2; i++) {
for (int j =-1; j <2; j++) {
if (Math.abs(i) != Math.abs(j)) {
sizes.add(getLegSize(n, m, i, j));
if (sizes.size() > 1)
return 0;
}
}
}
return sizes.contains(1) ? 0 : 1;
}
private int getLegSize(int i, int j, int iDir, int jDir) {
char ch = grid[i][j];
int res = 0;
while (inBounds(i, j) && grid[i][j]==ch) {
res++;
i+=iDir;
j+=jDir;
}
return res;
}
private boolean inBounds(int i, int j) {
return (i > -1 && i<grid.length && j >-1 && j < grid[0].length);
}
}