...

/

Solution: Regions Cut by Slashes

Solution: Regions Cut by Slashes

Let's solve the Regions Cut By Slashes problem using the Union Find pattern.

Statement

An n×nn \times n grid is composed of nn, 1×11 \times 1 squares, where each 1×11 \times 1 square consists of a “/”, “\”, or a blank space. These characters divide the square into adjacent regions.

Given the grid represented as a string array, return the number of regions.

Note:

  1. Backslash characters are escaped, so “\” is represented as “\\”.
  2. A 1×11 \times 1 square in the grid will be referred to as a box.

Constraints:

  • The grid consists of only “/”, “\”, or " " characters.
  • 1 \leq grid.length \leq 30

The following demonstration shows how the grid can be visualized:

Press + to interact
canvasAnimation-image
1 / 16

Solution

We can combine the smaller regions (represented by 1x1 boxes) into bigger ones to make it easier to determine the count of distinct regions overall. For this, we first divide each 1x1 box into four parts. Then, we start traversing the grid, visiting each box, and see what parts of each box can be merged. This is decided by the character which corresponds to a particular box. If it’s a "/" or a "\", out of the four parts, we merge the two parts above the slash into the same for the two parts below the slash. This results in a box now having only two regions overall (one above the slash and the other below the slash). However, if the character corresponding to the box is " ", we merge all four parts. To achieve this, we use the union find pattern. ...