Regions Cut By Slashes (LeetCode 959): Solution and Explanation
An n by n grid has cells that each hold a forward slash, a backslash or a blank. The slashes act as walls that run corner to corner inside their cells. Count how many separate regions the walls divide the whole square into.
Watch it run step by step
Try your own input and write the code →Intuition
The difficulty is that slashes split cells diagonally, while flood fill naturally works on whole cells and four-directional moves. You cannot just count cells, because one cell can belong to two different regions. You need a representation where the diagonal walls become ordinary blocked cells.
Upscaling does that. Replace every cell with a 3 by 3 block of pixels. A forward slash becomes the three pixels on the anti-diagonal of its block, from top-right to bottom-left, and a backslash becomes the three on the main diagonal. Blank cells leave all nine pixels open. Now the drawing is a plain binary grid, and the number of regions is the number of connected groups of open pixels, which is the number of islands problem in disguise.
Why 3 and not 2? With a 2 by 2 block, the open pixels in a narrow diagonal band, such as the strip between two parallel slashes, touch each other only at their corners. Four-directional flood fill cannot cross a corner, so one real region shatters into several pieces and the count comes out too high. Three pixels per side leave enough room that every region stays connected through shared edges, while each diagonal is still a solid wall.
Approach: Upscale to a 3 × 3 pixel grid and flood fill
- Create a
3nby3ngrid of zeros calledexpanded. - For each
/at(i, j), set the pixels(3i, 3j+2),(3i+1, 3j+1)and(3i+2, 3j)to 1. - For each backslash, set
(3i, 3j),(3i+1, 3j+1)and(3i+2, 3j+2)to 1. - Define
dfs(i, j)that returns on out-of-bounds or non-zero pixels, otherwise marks the pixel 2 and recurses in four directions. - Scan every pixel; each time an open pixel (0) is found, flood fill from it and increment
regions. - Return
regions.
Step-by-step example
grid = [" /", "/ "]
- The expanded grid is 6 by 6. The slash at row 0, column 1 fills pixels (0,5), (1,4) and (2,3).
- The slash at row 1, column 0 fills pixels (3,2), (4,1) and (5,0). Together they form one continuous diagonal wall from the top-right corner to the bottom-left corner.
- The scan starts at pixel (0,0), which is open. The flood fill covers the whole upper-left triangle and stops at the wall, so
regions = 1. - Continuing the scan, the first open pixel not yet filled is (1,5), just right of the wall. Flood fill from it covers the lower-right triangle, so
regions = 2. - No other open pixels remain, so the answer is 2.
Code: Python, Java, C++
1class Solution:
2 def regionsBySlashes(self, grid: List[str]) -> int:
3 n = len(grid)
4 expanded = [[0] * (3 * n) for _ in range(3 * n)]
5
6 for i in range(n):
7 for j in range(n):
8 if grid[i][j] == '/':
9 expanded[3*i][3*j+2] = 1
10 expanded[3*i+1][3*j+1] = 1
11 expanded[3*i+2][3*j] = 1
12 elif grid[i][j] == '\\':
13 expanded[3*i][3*j] = 1
14 expanded[3*i+1][3*j+1] = 1
15 expanded[3*i+2][3*j+2] = 1
16
17 def dfs(i, j):
18 if i < 0 or i >= 3*n or j < 0 or j >= 3*n or expanded[i][j] != 0:
19 return
20 expanded[i][j] = 2
21 dfs(i+1, j); dfs(i-1, j); dfs(i, j+1); dfs(i, j-1)
22
23 regions = 0
24 for i in range(3 * n):
25 for j in range(3 * n):
26 if expanded[i][j] == 0:
27 dfs(i, j)
28 regions += 1
29
30 return regions1class Solution {
2 int[][] expanded;
3 int size;
4
5 public int regionsBySlashes(String[] grid) {
6 int n = grid.length;
7 size = 3 * n;
8 expanded = new int[size][size];
9
10 for (int i = 0; i < n; i++) {
11 for (int j = 0; j < n; j++) {
12 if (grid[i].charAt(j) == '/') {
13 expanded[3*i][3*j+2] = 1;
14 expanded[3*i+1][3*j+1] = 1;
15 expanded[3*i+2][3*j] = 1;
16 } else if (grid[i].charAt(j) == '\\') {
17 expanded[3*i][3*j] = 1;
18 expanded[3*i+1][3*j+1] = 1;
19 expanded[3*i+2][3*j+2] = 1;
20 }
21 }
22 }
23
24 int regions = 0;
25 for (int i = 0; i < size; i++) {
26 for (int j = 0; j < size; j++) {
27 if (expanded[i][j] == 0) {
28 dfs(i, j);
29 regions++;
30 }
31 }
32 }
33
34 return regions;
35 }
36
37 void dfs(int i, int j) {
38 if (i < 0 || i >= size || j < 0 || j >= size || expanded[i][j] != 0) return;
39 expanded[i][j] = 2;
40 dfs(i+1, j); dfs(i-1, j); dfs(i, j+1); dfs(i, j-1);
41 }
42}1class Solution {
2public:
3 int regionsBySlashes(vector<string>& grid) {
4 int n = grid.size();
5 vector<vector<int>> expanded(3 * n, vector<int>(3 * n, 0));
6
7 for (int i = 0; i < n; i++) {
8 for (int j = 0; j < n; j++) {
9 if (grid[i][j] == '/') {
10 expanded[3*i][3*j+2] = 1;
11 expanded[3*i+1][3*j+1] = 1;
12 expanded[3*i+2][3*j] = 1;
13 } else if (grid[i][j] == '\\') {
14 expanded[3*i][3*j] = 1;
15 expanded[3*i+1][3*j+1] = 1;
16 expanded[3*i+2][3*j+2] = 1;
17 }
18 }
19 }
20
21 function<void(int, int)> dfs = [&](int i, int j) {
22 if (i < 0 || i >= 3*n || j < 0 || j >= 3*n || expanded[i][j] != 0) return;
23 expanded[i][j] = 2;
24 dfs(i+1, j); dfs(i-1, j); dfs(i, j+1); dfs(i, j-1);
25 };
26
27 int regions = 0;
28 for (int i = 0; i < 3 * n; i++) {
29 for (int j = 0; j < 3 * n; j++) {
30 if (expanded[i][j] == 0) {
31 dfs(i, j);
32 regions++;
33 }
34 }
35 }
36
37 return regions;
38 }
39};Time and space complexity
O(n²)
The expanded grid has 9n² pixels and each is visited a constant number of times by the scan and the flood fill.
O(n²)
The expanded grid stores 9n² values, and the recursion stack can grow to the size of a region in the worst case.
Other approaches
Union-find on four triangles (time O(n² α(n)), space O(n²))
Split each cell into four triangles (top, right, bottom, left). Union them inside a cell according to its character, and union adjacent triangles across cell borders. The number of sets is the answer.
Euler's formula counting (time O(n² α(n)), space O(n²))
Treat the grid lines and slashes as a planar graph and count regions from vertices and edges with union-find on lattice points, adding a region each time a new edge closes a cycle.
Common mistakes
- Scaling by 2 instead of 3. Open pixels in a thin diagonal band then touch only at corners, so one region splits into several and the answer is too large.
- Mixing up which diagonal each character uses. A forward slash runs from the top-right pixel to the bottom-left pixel of its block.
- Reading the backslash wrong in code. In a Python string literal the character is written
'\\', and comparing with a single backslash in source is a syntax error. - Hitting Python's recursion limit. A 30 by 30 grid expands to 8,100 pixels, and one winding region can recurse deeper than the default limit of 1,000, so raise it or use an explicit stack.
Frequently asked questions
Why scale each cell to 3 by 3 in Regions Cut By Slashes?
It turns diagonal walls into solid lines of blocked pixels while keeping every region connected through shared pixel edges. With a 2 by 2 scale, thin diagonal regions break into pieces that only touch at corners, which inflates the count.
Is Regions Cut By Slashes the same as number of islands?
After upscaling, yes. You count connected groups of open pixels with flood fill, exactly like counting islands of land.
Can it be solved with union-find?
Yes. Split each cell into four triangles, union them according to the slash, union neighbors across cell borders, and count the sets at the end.
What is the time complexity?
O(n²). The expanded grid has 9n² pixels and each is processed a constant number of times.