← Home

959. Regions Cut By Slashes

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
union-findC++Markdown
959

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 959. Regions Cut By Slashes, the solution in this repository is mainly a union-find solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: union-find.

The notes already sitting in the source point us in the right direction:

  • Approach 1: Union-Find

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are unite, regionsBySlashes.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 12 ms, faster than 71.71% of C++ online submissions for Regions Cut By Slashes.
02//Memory Usage: 9.9 MB, less than 50.00% of C++ online submissions for Regions Cut By Slashes.
03//Approach 1: Union-Find
04class DSU{
05public:
06    vector<int> parent;
07    
08    DSU(int N){
09        parent = vector<int>(N);
10        iota(parent.begin(), parent.end(), 0);
11    }
12    
13    int find(int x){
14        if(parent[x] != x){ //initial state
15            parent[x] = find(parent[x]);
16        }
17        return parent[x];
18    }
19    
20    void unite(int x, int y){
21        // not "parent[x] = find(parent[y]);"
22        // not "parent[y] = find(parent[x]);"
23        // combine two component's head together
24        parent[find(x)] = find(y);
25    }
26};
27
28class Solution {
29public:
30    int regionsBySlashes(vector<string>& grid) {
31        int N = grid.size();
32        //0,1,2,3 for north, west, east, south
33        DSU dsu = DSU(4*N*N);
34        for(int r = 0; r < N; r++){
35            for(int c = 0; c < N; c++){
36                //one grid has max of 4 regions
37                int root = 4 * (r*N+c);
38                char val = grid[r][c];
39                //Note here it is "!="
40                if(val != '\\'){
41                    //north and west are connected
42                    dsu.unite(root + 0, root + 1);
43                    //east and south are connected
44                    dsu.unite(root + 2, root + 3);
45                }
46                if(val != '/'){
47                    //north and east are connected
48                    dsu.unite(root + 0, root + 2);
49                    //west and south are connected
50                    dsu.unite(root + 1, root + 3);
51                }
52                
53                //connecting with other grids
54                //connect south of current grid and north of the grid below
55                if(r + 1 < N)
56                    dsu.unite(root + 3, (root + 4*N) + 0);
57                //north and upper's south
58                if(r - 1 >= 0)
59                    dsu.unite(root + 0, (root - 4*N) + 3);
60                //east and rhs's west
61                if(c + 1 < N)
62                    dsu.unite(root + 2, (root + 4) + 1);
63                //west and lhs's east
64                if(c - 1 >= 0)
65                    dsu.unite(root + 1, (root - 4) + 2);
66            }
67        }
68        
69        int ans = 0;
70        for(int x = 0; x < 4*N*N; x++){
71            if(dsu.find(x) == x)
72                ans++;
73        }
74        
75        return ans;
76    }
77};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.