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 '/', a '\' or a blank ' '. Each slash is a wall drawn from one corner of its square to the opposite corner, and together the walls cut the grid into separate areas, called regions. Given the grid as an array of strings grid, one string per row, return the number of regions. In Java source a backslash is written "\\", so the examples show it doubled.

Example 1
Input: grid = [" /","/ "]
Output: 2
Explanation: the two slashes form one diagonal line across the grid.
Example 2
Input: grid = [" /","  "]
Output: 1
Explanation: a single slash does not cut anything off.
Example 3
Input: grid = ["/\\","\\/"]
Output: 5
Explanation: the four slashes form a diamond. The inside is one region and the four corners are four more.
Solution

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: '/' leaves a top-left and a bottom-right half, while '\' leaves a top-right and a bottom-left half. Working out which half of one square touches which half of its neighbour gets messy.

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.

Example 3 as a 2 by 2 grid. Each square is cut into four triangles, 0 top, 1 right, 2 bottom, 3 left. The four slashes form a diamond: the eight triangles inside it make the inside region, and the four corners make four corner regions of two triangles each, 5 in all.

Start with the square in row 0, column 0. It holds '/', which keeps triangles 0 and 3 (top and left) apart from triangles 1 and 2 (right and bottom). Triangles 0 and 3 are blue, so they belong to a corner region. Triangles 1 and 2 are orange.

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 r and column c is square number r * n + c. Its four triangles get the ids 4 * (r * n + c) plus 0, 1, 2 or 3. In Example 3, n is 2, so the square in row 1, column 0 is square 2 and owns the triangles 8 to 11. The whole grid has 4n² triangles.

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 parent, holding another triangle of its group. At the start, each triangle is its own parent. Following parent from any triangle always ends at a triangle that is its own parent, called the root of the group. The method find does that climb.

Two triangles are in the same group exactly when find gives the same root for both. To join them, the method union finds both roots and, if they differ, points one root at the other. Every triangle of the first group now climbs on to the second root.

Chains of parents can grow long as groups merge. So while find climbs, it points each triangle it passes at its grandparent, the parent of its parent. Later climbs from those triangles take about half as many steps, which is why this trick is called path halving.

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 union that merges two different groups lowers it by one, and a union of two triangles already together changes nothing. A single blank square shows it: four triangles, three merges, one region. A single '/' makes two merges and leaves 2.

Java Solution

The method regionsBySlashes works in these steps:

  1. First, create the array parent with one entry for each of the 4 * n * n triangles, and set parent[i] = i so every triangle is its own group. The counter regions starts at the number of triangles.
  2. Visit every square with two loops, one inside the other: the outer loop moves r over the rows and the inner loop moves c over the columns. For each square, compute base, the id of its top triangle, and read its character into ch.
  3. Join the triangles inside the square according to ch: two union calls for a slash, three for a blank.
  4. 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.
  5. Inside union, find climbs to both roots. When the roots differ, one is pointed at the other and regions goes down by one.
  6. When the loops are done, regions holds the number of groups, and the method returns it.

The main method runs the three examples, a single blank square, a single '/', two long diagonals crossing as an X, and a grid with three slashes. The helper show prints each grid row by row between bars, so the blanks stay visible, and then the count.

Java
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:

Output
| /|
|/ |
regions: 2

| /|
|  |
regions: 1

|/\|
|\/|
regions: 5

| |
regions: 1

|/|
regions: 2

|\/|
|/\|
regions: 4

|//|
|/ |
regions: 3

The grid |/\| over |\/| is the diamond from Example 3, and its count of 5 matches the picture. The one-square grids | | and |/| give 1 and 2, as the three merges of a blank square and the two merges of a slash predicted.

Look at |\/| over |/\| next. Its two long diagonals cross in the middle of the grid and cut it into four, so it prints 4. In the last grid, |//| over |/ |, the slash in row 0, column 0 cuts off the top-left corner. The other two slashes form one long diagonal that splits the rest in two, so the count is 3.

The two slash cases are easy to swap by accident. A copy of this program with the two slash tests exchanged prints regions: 3 for Example 1 and regions: 4 for Example 3. It joins the triangles on opposite sides of every slash, which amounts to reading each slash as tilted the other way.

Complexity

The work is one visit to each of the n² squares, with at most five union calls on each.

  • Time: O(n² log n), because the n² squares make at most 5n² union calls, and with path halving each find among the 4n² triangles costs O(log n) steps when averaged over all the calls.
  • Space: O(n²), because the parent array holds one entry for each of the 4n² triangles, four for every square of the grid.

Counting groups with union-find on a plain graph is shown in Number of Connected Components.