Regions Cut By Slashes
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Union Find.
Regions Cut By Slashes
An grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space. These characters divide the square into contiguous regions. Return the number of regions.
Visualization (4 per cell)
Divide each 1x1 cell into 4 triangles:
/\
/ 0\
<3 1>
\ 2/
\/ - '/' connects 0-3 and 1-2.
- '\' connects 0-1 and 2-3.
- ' ' connects 0-1-2-3.
Examples
Input: grid = [" /","/ "]
Output: 2
Approach 1
Level II: BFS (Grid Expansion)
Intuition
Scale the grid into a binary grid. Map '/' and '\' to sets of 1s in the 3x3 block. Then, use standard BFS or DFS to count connected components of 0s. This is more memory-intensive but conceptually simpler than triangle mapping.
⏱ O(N^2).💾 O(N^2).
Approach 2
Level III: Union-Find (Internal Grid Mapping)
Intuition
Represent each cell by 4 distinct nodes. Union neighboring triangles within the same cell based on the character ('/', '\', or ' '). Then, union adjacent triangles of neighboring cells. The final component count is the number of regions.
⏱ O(N^2 \cdot \alpha(N^2)).💾 O(N^2).
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.