Regions Cut by Slashes

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

An n x n 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.

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

Note that backslash characters are escaped, so a '\' is represented as "\\" in the input.

Examples

Example 1:

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

Output: 2

Explanation: The 2x2 grid with two / characters creates 2 regions.

Example 2:

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

Output: 1

Explanation: The single / does not fully partition the grid.

Example 3:

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

Output: 5

Explanation: The grid forms a diamond pattern with 5 separate regions.

Constraints

  • n == grid.length == grid[i].length
  • 1 <= n <= 30
  • grid[i][j] is '/', '\', or ' '
Source: Union Find pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle