Regions Cut By Slashes
Count the areas that slashes cut a square grid into, by splitting every square into four triangles.
An n × n grid is made of 1 × 1 squares, and each square holds a '/''\'' 'grid"\\"
Example 1
Output: 2
Explanation: the two slashes form one diagonal line across the grid.
Example 2
Output: 1
Explanation: a single slash does not cut anything off.
Example 3
Output: 5
Explanation: the four slashes form a diamond. The inside is one region and the four corners are four more.
The Idea
Picture a square courtyard paved with tiles, one tile for each square of the grid. On some tiles a low wall runs from one corner to the opposite corner. A region is an area you can walk around in without stepping over a wall, and the question is how many such areas the walls create.
In Example 3 the courtyard has 2 × 2 tiles, and the four walls meet in a diamond. Inside the diamond is one area. Outside it, each corner of the courtyard is shut off on its own, which makes 5 regions. That is easy to see in a drawing, but how can a program tell which parts of the grid are connected?
A square with a slash has two halves, and a blank square is one piece. The trouble is that the halves differ: '/''\'
It gets simple once every square is cut the same way, along both of its diagonals. That gives four triangles per square: top, right, bottom and left, numbered 0, 1, 2 and 3. A slash always lies on one of the two diagonals, so it never cuts through a triangle. It only stands between some of them. Look at the picture below.
Start with the square in row 0, column 0. It holds '/'
Now look across the edge below that square. Its triangle 2 touches triangle 0 of the square in row 1, column 0, and no slash ever lies on an edge between two squares. So those two triangles are in the same region. Following such touches from triangle to triangle collects the eight orange triangles into the inside region. The blue pairs stay apart and form the four corner regions: 1 + 4 = 5.
So the problem becomes a matter of groups. Every triangle starts alone. Two triangles that touch with no slash between them are put in the same group, and the answer is the number of groups at the end. A structure built for exactly this, merging groups and asking which group an item is in, is known as union-find (also called a disjoint set union).
Solution Approach
Turning that idea into code means settling five things: how to number the triangles, what to join inside a square, what to join across squares, how to track the groups, and how to count them.
Numbering the triangles
How does the code name one triangle? Counting squares row by row, the square in row rcr * n + c4 * (r * n + c)
Joining triangles inside a square
Which triangles of one square belong together? It depends on what the square holds:
runs from the bottom-left corner to the top-right corner: top joins left, and right joins bottom.'/' runs from the top-left corner to the bottom-right corner: top joins right, and bottom joins left.'\'- A blank square has no wall, so all four triangles join.
Joining triangles across squares
Which triangles of neighbouring squares touch? The bottom triangle of a square shares an edge with the top triangle of the square below it. The right triangle shares an edge with the left triangle of the square to its right. A slash never lies on such an edge, so these pairs are always joined.
Each square only needs to look down and to the right. The edge above a square is the edge below the square above it, and that square already joined across it.
Keeping track of the groups
How can the code tell whether two triangles are already in the same group? Give every triangle an entry in an array parentparentfind
Two triangles are in the same group exactly when findunion
Chains of parents can grow long as groups merge. So while find
Counting the regions
Do we need a separate pass at the end to count roots? No. Keep a counter that starts at 4n², one group per triangle. Each unionunion'/'
Java Solution
The method regionsBySlashes
- First, create the array
with one entry for each of theparent triangles, and set4 * n * n so every triangle is its own group. The counterparent[i] = i starts at the number of triangles.regions - Visit every square with two loops, one inside the other: the outer loop moves
over the rows and the inner loop movesr over the columns. For each square, computec , the id of its top triangle, and read its character intobase .ch - Join the triangles inside the square according to
: twoch calls for a slash, three for a blank.union - For the same square, join its bottom triangle with the top triangle of the square below, when there is a row below. Then join its right triangle with the left triangle of the square to the right, when there is a column to the right.
- Inside
,union climbs to both roots. When the roots differ, one is pointed at the other andfind goes down by one.regions - When the loops are done,
holds the number of groups, and the method returns it.regions
The main'/'show
public class RegionsCutBySlashes {
private int[] parent;
private int regions;
// Each square is split into 4 triangles: 0 = top, 1 = right, 2 = bottom, 3 = left.
public int regionsBySlashes(String[] grid) {
int n = grid.length;
parent = new int[4 * n * n];
for (int i = 0; i < parent.length; i++) {
parent[i] = i; // every triangle starts as its own group
}
regions = parent.length;
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
int base = 4 * (r * n + c); // id of this square's top triangle
char ch = grid[r].charAt(c);
if (ch == '/') { // top + left, right + bottom
union(base, base + 3);
union(base + 1, base + 2);
} else if (ch == '\\') { // top + right, bottom + left
union(base, base + 1);
union(base + 2, base + 3);
} else { // blank: all four join
union(base, base + 1);
union(base + 1, base + 2);
union(base + 2, base + 3);
}
if (r + 1 < n) { // bottom meets the top of the square below
union(base + 2, 4 * ((r + 1) * n + c));
}
if (c + 1 < n) { // right meets the left of the square to the right
union(base + 1, 4 * (r * n + c + 1) + 3);
}
}
}
return regions;
}
private int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]]; // skip one step up for next time
x = parent[x];
}
return x;
}
private void union(int a, int b) {
int ra = find(a);
int rb = find(b);
if (ra != rb) { // two different groups become one
parent[ra] = rb;
regions--;
}
}
static void show(String... grid) {
for (String row : grid) {
System.out.println("|" + row + "|");
}
System.out.println("regions: " + new RegionsCutBySlashes().regionsBySlashes(grid));
System.out.println();
}
public static void main(String[] args) {
show(" /", "/ ");
show(" /", " ");
show("/\\", "\\/");
show(" ");
show("/");
show("\\/", "/\\");
show("//", "/ ");
}
}
Running it prints:
| /|
|/ |
regions: 2
| /|
| |
regions: 1
|/\|
|\/|
regions: 5
| |
regions: 1
|/|
regions: 2
|\/|
|/\|
regions: 4
|//|
|/ |
regions: 3
The grid |/\||\/|| ||/|
Look at |\/||/\||//||/ |
The two slash cases are easy to swap by accident. A copy of this program with the two slash tests exchanged prints regions: 3regions: 4
Complexity
The work is one visit to each of the n² squares, with at most five union
- Time: O(n² log n), because the n² squares make at most 5n²
calls, and with path halving eachunion among the 4n² triangles costs O(log n) steps when averaged over all the calls.find - Space: O(n²), because the
array holds one entry for each of the 4n² triangles, four for every square of the grid.parent
Counting groups with union-find on a plain graph is shown in