Regions Cut By Slashes

Medium Topics Company Tags

A square grid is represented by n strings of length n. Each character describes a unit square: a forward slash joins its bottom-left and top-right corners, a backslash joins its top-left and bottom-right corners, and a space leaves the square undivided.

The diagonal segments and the outside boundary divide the grid into connected regions. Return the number of regions inside the grid. Regions can connect across an unobstructed cell edge, but touching only at a point does not join them.

Input strings use JSON escaping, so one backslash is written as two backslashes inside a quoted string. Spaces inside the strings are grid cells and must be preserved.

Example 1:

Regions Cut By Slashes, example 1: illustration of the example

Input: grid = ["/"]

Output: 2

Explanation: One diagonal crosses the only square from corner to corner, separating it into two triangular regions.

Example 2:

Regions Cut By Slashes, example 2: illustration of the example

Input: grid = [" "]

Output: 1

Explanation: The single blank square has no internal boundary, so it forms one connected region.

Example 3:

Regions Cut By Slashes, example 3: illustration of the example

Input: grid = ["//","//"]

Output: 4

Explanation: The four slash segments join into three parallel diagonal boundaries across the grid. These boundaries separate the square into four regions.

Constraints:

  • 1 <= grid.length <= 30
  • Every row has exactly grid.length characters.
  • Each character is a forward slash, a backslash, or a space.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.