Skip to main content
LeetCode 959, Medium. Topics: Array, Hash Table, Depth-First Search, Breadth-First Search, Union Find, Matrix. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 16 parametrized pytest cases, and a playground notebook:

Problem

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

Examples

Example 1
Example 2
Example 3

Constraints

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

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026