Search⌘ K
AI Features

Regions Cut by Slashes

Explore how to apply Union Find to solve the problem of counting regions cut by slashes in an n by n grid. This lesson helps you understand graph connectivity and implement solutions for common coding interview questions efficiently.

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 adjacent 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 the “/”, “\”, or " " characters.
  • 1 \leq grid.length \leq 30

The following illustration shows how the grid can be visualized:

canvasAnimation-image
1 / 16

Examples

canvasAnimation-image
1 / 3

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Regions Cut By Slashes

1.

What is the output if the following grid is given as input?

grid = ["\\/", “/\\”]

A.

2

B.

3

C.

4

D.

5


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in main.js in the following coding playground. You will need the provided supporting code to implement your solution.

JavaScript
usercode > main.js
/*
⬅️ We have provided a union_find.js file under the "Files" tab
of this widget. You can use this file to build your solution.
*/
import UnionFind from './union_find.js'
function regionsBySlashes(grid){
// Replace this placeholder return statement with your code
return -1;
}
export { regionsBySlashes };
Regions Cut by Slashes