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 '\\'.

Input & Output

Example 1 — Basic Slash Division
$ Input: grid = [" /","/ "]
Output: 2
💡 Note: The 2x2 grid has a '/' in positions (0,1) and (1,0). These slashes divide the grid into 2 separate regions: one triangle-shaped region in the top-left and bottom-right corners, and another in the top-right and bottom-left corners.
Example 2 — Backslash Division
$ Input: grid = [" \\","\\ "]
Output: 2
💡 Note: The backslashes create a different pattern than forward slashes, but still divide the 2x2 grid into 2 regions. The backslashes connect opposite corners, creating 2 triangle-shaped regions.
Example 3 — No Division
$ Input: grid = [" "," "]
Output: 1
💡 Note: All cells are empty spaces, so there are no barriers dividing the grid. The entire 2x2 area forms one single connected region.

Constraints

  • n == grid.length == grid[i].length
  • 1 ≤ n ≤ 30
  • grid[i][j] is either '/', '\\', or ' '

Visualization

Tap to expand
Regions Cut By Slashes - 3x Grid Scaling with DFS INPUT Original 2x2 Grid [0] [1] Input Array: grid = [" /","/ "] " /" means space + slash "/ " means slash + space = empty space = slash / ALGORITHM STEPS 1 Scale 3x Each cell becomes 3x3 2 Draw Slashes Mark 1s on diagonal 3 DFS Flood Fill Count connected 0-regions 4 Count Regions Each DFS = 1 region Scaled 6x6 Grid: R1 R2 FINAL RESULT Two separate regions found: Region 1 Upper-right area (above the slashes) Region 2 Lower-left area (below the slashes) Output: 2 regions OK - Verified Key Insight: Scaling each cell to 3x3 allows us to represent diagonal slashes as filled cells in a binary grid. A "/" fills cells at positions (0,2), (1,1), (2,0). A "\" fills (0,0), (1,1), (2,2). Standard DFS flood-fill then counts connected components of 0s (empty spaces). TutorialsPoint - Regions Cut By Slashes | 3x Grid Scaling with DFS Approach
Asked in
Google 12 Amazon 8 Facebook 6
52.0K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen