959. Regions Cut By Slashes
Problem Description
You are given an n x n
grid where each cell contains one of three characters:
'/'
- a forward slash'\'
- a backslash (represented as'\\'
in the input due to escaping)' '
- a blank space
These characters divide the grid into distinct contiguous regions. When you draw the slashes in each cell, they create boundaries that separate different areas.
For example:
- A
'/'
in a cell creates a diagonal line from the bottom-left corner to the top-right corner - A
'\'
creates a diagonal line from the top-left corner to the bottom-right corner - A blank space
' '
means no diagonal line in that cell
Your task is to count the total number of separate regions formed by these slashes.
The key insight is that each 1Γ1 cell can be divided into 4 triangular parts by its diagonals. The solution uses Union-Find to track which triangular parts are connected:
- Each cell is split into 4 triangles (numbered 0-3: top, right, bottom, left)
- Adjacent cells share edges, so their corresponding triangles need to be connected
- The slash characters determine which triangles within a cell are connected
- A
'/'
connects the top with left triangles, and right with bottom triangles - A
'\'
connects the top with right triangles, and left with bottom triangles - A blank space connects all four triangles within the cell
The algorithm starts with n * n * 4
separate components (4 triangles per cell) and uses union operations to merge connected components. The final count of distinct components gives the number of regions.
Flowchart Walkthrough
First, let's pin down the algorithm using the Flowchart. Here's a step-by-step walkthrough:
Is it a graph?
- Yes: The problem involves regions that are connected to each other. Each region can be thought of as a node, and adjacent regions (those that share boundaries) have edges between them. The slashes create boundaries that define how these regions connect.
Is it a tree?
- No: The regions form a general graph structure, not a tree. There can be multiple disconnected components (separate regions), and within each component, there might be cycles depending on how the slashes are arranged.
Is the problem related to directed acyclic graphs?
- No: The problem deals with undirected connectivity between regions. The connections between adjacent areas don't have a direction.
Is the problem related to shortest paths?
- No: We're not trying to find the shortest path between regions. We're counting the total number of distinct regions.
Does the problem involve connectivity?
- Yes: The core of the problem is determining which parts of the grid are connected to form a single region. We need to identify all connected components in the graph.
Disjoint Set Union
- Yes: DSU (Union-Find) is the ideal approach here. We start with many small components (the triangular parts of each cell) and merge them based on the slash patterns and adjacency rules.
Conclusion: The flowchart leads us to using Disjoint Set Union (DSU/Union-Find) for this connectivity problem. While the flowchart suggests DSU rather than DFS directly, both approaches can solve connectivity problems. The solution uses DSU to efficiently track and merge connected components, ultimately counting the number of distinct regions.
Intuition
The key insight is to transform this visual problem into a connectivity problem. When we look at a grid with slashes, we're essentially looking at lines that divide space into separate regions. But how do we represent this computationally?
Imagine each 1Γ1 cell as being divided into 4 triangular pieces by drawing both possible diagonals (forming an X). Even though we only draw one slash (or none) per cell, thinking of it as 4 triangles gives us a consistent way to model the problem:
- Triangle 0: top
- Triangle 1: right
- Triangle 2: bottom
- Triangle 3: left
Now, when a slash is present:
- A
'/'
slash runs from bottom-left to top-right, keeping the top-left triangles together and bottom-right triangles together - A
'\'
slash runs from top-left to bottom-right, keeping the top-right triangles together and bottom-left triangles together - A blank space means all 4 triangles in that cell are connected
The brilliant part is realizing that adjacent cells share edges. For example:
- The bottom triangle of cell
(i,j)
touches the top triangle of cell(i+1,j)
- The right triangle of cell
(i,j)
touches the left triangle of cell(i,j+1)
This means we need to connect these triangles across cell boundaries.
We start with n * n * 4
separate components (4 triangles for each of the n * n
cells). As we process each cell:
- We connect triangles within the cell based on the slash type
- We connect triangles to adjacent cells along shared edges
Every union operation reduces the number of components by 1. After processing all cells, the remaining number of components equals the number of distinct regions in the grid.
This approach elegantly converts a geometric visualization problem into a graph connectivity problem that can be solved efficiently with Union-Find.
Learn more about Depth-First Search, Breadth-First Search and Union Find patterns.
Solution Approach
The solution implements a Union-Find (Disjoint Set Union) data structure to track and merge connected triangular components.
Data Structure Setup:
- Create a parent array
p
of sizen * n * 4
where each element initially points to itself - Each cell
(i, j)
has 4 triangles indexed as:4 * (i * n + j) + triangle_number
- Initialize
size
ton * n * 4
(total number of components)
Union-Find Operations:
find(x)
: Returns the root parent of componentx
with path compression for optimizationunion(a, b)
: Merges two components if they have different roots, decreasingsize
by 1
Processing Each Cell:
For each cell at position (i, j)
with index k = i * n + j
:
-
Connect to Adjacent Cells:
- If not at bottom edge (
i < n - 1
): Connect bottom triangle of current cell (4*k + 2
) with top triangle of cell below ((k + n) * 4
) - If not at right edge (
j < n - 1
): Connect right triangle of current cell (4*k + 1
) with left triangle of cell to the right ((k + 1) * 4 + 3
)
- If not at bottom edge (
-
Handle Internal Connections Based on Character:
'/'
: Connect triangles 0β3 (topβleft) and 1β2 (rightβbottom)'\'
: Connect triangles 0β1 (topβright) and 2β3 (bottomβleft)' '
: Connect all four triangles (0β1, 1β2, 2β3)
Algorithm Flow:
1. Initialize n*n*4 components 2. For each cell (i,j): a. Connect to adjacent cells (bottom and right neighbors) b. Based on slash type, connect internal triangles c. Each union reduces component count by 1 3. Return final component count (size)
The time complexity is O(nΒ² * Ξ±(n))
where Ξ±
is the inverse Ackermann function (practically constant), and space complexity is O(nΒ²)
for the parent array.
Ready to land your dream job?
Unlock your dream job with a 3-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through a small 2Γ2 grid example:
grid = [" /", "/ "]
Initial Setup:
- We have 2Γ2 = 4 cells, each divided into 4 triangles
- Total components = 2 * 2 * 4 = 16 components
- Each triangle gets an ID from 0 to 15
Cell Numbering and Triangle IDs:
Cell (0,0): triangles 0,1,2,3 Cell (0,1): triangles 4,5,6,7 Cell (1,0): triangles 8,9,10,11 Cell (1,1): triangles 12,13,14,15
Visual representation of triangles in each cell:
0 (each cell divided like this)
/ \
3 1
\ /
2
Step 1: Process Cell (0,0) - contains ' ' (blank)
- Connect to adjacent cells:
- Bottom triangle 2 connects to top triangle 8 of cell (1,0) below
- Right triangle 1 connects to left triangle 7 of cell (0,1) to the right
- Internal connections for blank space:
- Connect 0β1, 1β2, 2β3 (all four triangles connected)
- Components after: 16 - 5 unions = 11
Step 2: Process Cell (0,1) - contains '/'
- Connect to adjacent cells:
- Bottom triangle 6 connects to top triangle 12 of cell (1,1) below
- No right neighbor (edge of grid)
- Internal connections for '/':
- Connect 4β7 (topβleft) and 5β6 (rightβbottom)
- Components after: 11 - 3 unions = 8
Step 3: Process Cell (1,0) - contains '/'
- Connect to adjacent cells:
- No bottom neighbor (edge of grid)
- Right triangle 9 connects to left triangle 15 of cell (1,1) to the right
- Internal connections for '/':
- Connect 8β11 (topβleft) and 9β10 (rightβbottom)
- Components after: 8 - 3 unions = 5
Step 4: Process Cell (1,1) - contains ' ' (blank)
- Connect to adjacent cells:
- No bottom or right neighbors (corner of grid)
- Internal connections for blank space:
- Connect 12β13, 13β14, 14β15 (all four triangles connected)
- Components after: 5 - 3 unions = 2
Final Result: 2 regions
The algorithm correctly identifies that this grid forms 2 separate regions - one large connected region and one triangular region in the corner.
Solution Implementation
1class Solution:
2 def regionsBySlashes(self, grid: List[str]) -> int:
3 """
4 Count the number of regions formed by slashes in a grid.
5 Each cell is divided into 4 triangular parts (numbered 0-3):
6
7 0
8 -----
9 |\ 3 /|
10 | \ / |
11 |1 X 2|
12 | / \ |
13 |/ 1 \|
14 -----
15 2
16 """
17
18 def find(node: int) -> int:
19 """Find the root parent of a node with path compression."""
20 if parent[node] != node:
21 parent[node] = find(parent[node]) # Path compression
22 return parent[node]
23
24 def union(node_a: int, node_b: int) -> None:
25 """Union two nodes by connecting their root parents."""
26 root_a = find(node_a)
27 root_b = find(node_b)
28
29 if root_a != root_b:
30 parent[root_a] = root_b
31 nonlocal region_count
32 region_count -= 1 # Merge two regions into one
33
34 # Initialize variables
35 grid_size = len(grid)
36 region_count = grid_size * grid_size * 4 # Each cell has 4 triangular regions
37 parent = list(range(region_count)) # Initially, each region is its own parent
38
39 # Process each cell in the grid
40 for row_idx, row in enumerate(grid):
41 for col_idx, slash_char in enumerate(row):
42 # Calculate base index for current cell's 4 regions
43 cell_base_idx = row_idx * grid_size + col_idx
44
45 # Connect with bottom neighbor cell (if not at bottom edge)
46 if row_idx < grid_size - 1:
47 # Connect bottom triangle of current cell with top triangle of cell below
48 union(4 * cell_base_idx + 2,
49 (cell_base_idx + grid_size) * 4 + 0)
50
51 # Connect with right neighbor cell (if not at right edge)
52 if col_idx < grid_size - 1:
53 # Connect right triangle of current cell with left triangle of right cell
54 union(4 * cell_base_idx + 1,
55 (cell_base_idx + 1) * 4 + 3)
56
57 # Handle slash characters within the current cell
58 if slash_char == '/':
59 # '/' connects top-left and bottom-right triangles
60 union(4 * cell_base_idx + 0, 4 * cell_base_idx + 3) # Top with left
61 union(4 * cell_base_idx + 1, 4 * cell_base_idx + 2) # Right with bottom
62 elif slash_char == '\\':
63 # '\' connects top-right and bottom-left triangles
64 union(4 * cell_base_idx + 0, 4 * cell_base_idx + 1) # Top with right
65 union(4 * cell_base_idx + 2, 4 * cell_base_idx + 3) # Bottom with left
66 else: # Empty space ' '
67 # Connect all four triangles in the cell
68 union(4 * cell_base_idx + 0, 4 * cell_base_idx + 1) # Top with right
69 union(4 * cell_base_idx + 1, 4 * cell_base_idx + 2) # Right with bottom
70 union(4 * cell_base_idx + 2, 4 * cell_base_idx + 3) # Bottom with left
71
72 return region_count
73
1class Solution {
2 // Parent array for Union-Find data structure
3 private int[] parent;
4 // Counter for number of distinct regions
5 private int regionCount;
6
7 /**
8 * Counts the number of regions formed by slashes in a grid.
9 * Each cell is divided into 4 triangular parts (numbered 0-3):
10 * 0: top triangle
11 * 1: right triangle
12 * 2: bottom triangle
13 * 3: left triangle
14 *
15 * @param grid Array of strings representing the n x n grid
16 * @return Number of distinct regions
17 */
18 public int regionsBySlashes(String[] grid) {
19 int n = grid.length;
20 // Each cell has 4 parts, so total parts = n * n * 4
21 regionCount = n * n * 4;
22 parent = new int[regionCount];
23
24 // Initialize Union-Find: each part is its own parent initially
25 for (int i = 0; i < parent.length; i++) {
26 parent[i] = i;
27 }
28
29 // Process each cell in the grid
30 for (int row = 0; row < n; row++) {
31 for (int col = 0; col < n; col++) {
32 // Calculate base index for current cell's 4 parts
33 int cellIndex = row * n + col;
34
35 // Connect bottom triangle of current cell with top triangle of cell below
36 if (row < n - 1) {
37 union(4 * cellIndex + 2, (cellIndex + n) * 4);
38 }
39
40 // Connect right triangle of current cell with left triangle of cell to the right
41 if (col < n - 1) {
42 union(4 * cellIndex + 1, (cellIndex + 1) * 4 + 3);
43 }
44
45 // Handle internal connections based on the character in current cell
46 char cellChar = grid[row].charAt(col);
47 if (cellChar == '/') {
48 // '/' connects top-left and bottom-right
49 union(4 * cellIndex, 4 * cellIndex + 3); // Connect top and left triangles
50 union(4 * cellIndex + 1, 4 * cellIndex + 2); // Connect right and bottom triangles
51 } else if (cellChar == '\\') {
52 // '\' connects top-right and bottom-left
53 union(4 * cellIndex, 4 * cellIndex + 1); // Connect top and right triangles
54 union(4 * cellIndex + 2, 4 * cellIndex + 3); // Connect bottom and left triangles
55 } else {
56 // Empty space ' ' connects all four triangles
57 union(4 * cellIndex, 4 * cellIndex + 1); // Connect top and right
58 union(4 * cellIndex + 1, 4 * cellIndex + 2); // Connect right and bottom
59 union(4 * cellIndex + 2, 4 * cellIndex + 3); // Connect bottom and left
60 }
61 }
62 }
63
64 return regionCount;
65 }
66
67 /**
68 * Find operation with path compression for Union-Find.
69 *
70 * @param x The element to find the root of
71 * @return The root parent of element x
72 */
73 private int find(int x) {
74 if (parent[x] != x) {
75 // Path compression: make x point directly to root
76 parent[x] = find(parent[x]);
77 }
78 return parent[x];
79 }
80
81 /**
82 * Union operation for Union-Find.
83 * Connects two elements by joining their root parents.
84 *
85 * @param a First element to union
86 * @param b Second element to union
87 */
88 private void union(int a, int b) {
89 int rootA = find(a);
90 int rootB = find(b);
91
92 // If already in same set, no union needed
93 if (rootA == rootB) {
94 return;
95 }
96
97 // Union the two sets and decrease region count
98 parent[rootA] = rootB;
99 regionCount--;
100 }
101}
102
1class Solution {
2public:
3 vector<int> parent;
4 int componentCount;
5
6 int regionsBySlashes(vector<string>& grid) {
7 int gridSize = grid.size();
8
9 // Each cell is divided into 4 triangular regions (top, right, bottom, left)
10 // Total regions = gridSize * gridSize * 4
11 componentCount = gridSize * gridSize * 4;
12 parent.resize(componentCount);
13
14 // Initialize each region as its own parent (separate component)
15 for (int i = 0; i < componentCount; ++i) {
16 parent[i] = i;
17 }
18
19 // Process each cell in the grid
20 for (int row = 0; row < gridSize; ++row) {
21 for (int col = 0; col < gridSize; ++col) {
22 // Calculate base index for current cell's 4 regions
23 int cellIndex = row * gridSize + col;
24 int baseRegionIndex = cellIndex * 4;
25
26 // Connect bottom region of current cell with top region of cell below
27 if (row < gridSize - 1) {
28 int belowCellBaseIndex = (cellIndex + gridSize) * 4;
29 merge(baseRegionIndex + 2, belowCellBaseIndex + 0);
30 }
31
32 // Connect right region of current cell with left region of cell to the right
33 if (col < gridSize - 1) {
34 int rightCellBaseIndex = (cellIndex + 1) * 4;
35 merge(baseRegionIndex + 1, rightCellBaseIndex + 3);
36 }
37
38 // Handle the slash character in current cell
39 char slashChar = grid[row][col];
40
41 if (slashChar == '/') {
42 // Forward slash: connect top-left and bottom-right
43 merge(baseRegionIndex + 0, baseRegionIndex + 3); // top with left
44 merge(baseRegionIndex + 1, baseRegionIndex + 2); // right with bottom
45 }
46 else if (slashChar == '\\') {
47 // Backslash: connect top-right and bottom-left
48 merge(baseRegionIndex + 0, baseRegionIndex + 1); // top with right
49 merge(baseRegionIndex + 2, baseRegionIndex + 3); // bottom with left
50 }
51 else {
52 // Space: connect all 4 regions together
53 merge(baseRegionIndex + 0, baseRegionIndex + 1); // top with right
54 merge(baseRegionIndex + 1, baseRegionIndex + 2); // right with bottom
55 merge(baseRegionIndex + 2, baseRegionIndex + 3); // bottom with left
56 }
57 }
58 }
59
60 return componentCount;
61 }
62
63private:
64 // Merge two components into one
65 void merge(int regionA, int regionB) {
66 int rootA = find(regionA);
67 int rootB = find(regionB);
68
69 // Already in same component
70 if (rootA == rootB) {
71 return;
72 }
73
74 // Union the two components
75 parent[rootA] = rootB;
76 componentCount--; // Decrease total component count
77 }
78
79 // Find root parent with path compression
80 int find(int region) {
81 if (parent[region] != region) {
82 parent[region] = find(parent[region]); // Path compression
83 }
84 return parent[region];
85 }
86};
87
1// Parent array for Union-Find data structure
2let parent: number[];
3// Number of distinct regions
4let regionCount: number;
5
6/**
7 * Find the root parent of a node with path compression
8 * @param x - The node to find the root parent for
9 * @returns The root parent of the node
10 */
11function find(x: number): number {
12 if (parent[x] !== x) {
13 // Path compression: directly connect node to root
14 parent[x] = find(parent[x]);
15 }
16 return parent[x];
17}
18
19/**
20 * Union two nodes into the same set
21 * @param a - First node
22 * @param b - Second node
23 */
24function union(a: number, b: number): void {
25 const rootA = find(a);
26 const rootB = find(b);
27
28 // If roots are different, merge them
29 if (rootA !== rootB) {
30 parent[rootA] = rootB;
31 regionCount--;
32 }
33}
34
35/**
36 * Count the number of regions formed by slashes in a grid
37 * Each cell is divided into 4 triangular parts:
38 * - 0: top triangle
39 * - 1: right triangle
40 * - 2: bottom triangle
41 * - 3: left triangle
42 *
43 * @param grid - Array of strings where each character is ' ', '/', or '\\'
44 * @returns Number of distinct regions
45 */
46function regionsBySlashes(grid: string[]): number {
47 const gridSize = grid.length;
48 // Each cell has 4 triangular parts
49 const totalParts = gridSize * gridSize * 4;
50
51 // Initialize Union-Find structure
52 regionCount = totalParts;
53 parent = Array.from({ length: totalParts }, (_, index) => index);
54
55 for (let row = 0; row < gridSize; row++) {
56 for (let col = 0; col < gridSize; col++) {
57 // Calculate base index for current cell's 4 parts
58 const cellIndex = row * gridSize + col;
59 const baseIndex = cellIndex * 4;
60
61 // Connect bottom triangle of current cell with top triangle of cell below
62 if (row < gridSize - 1) {
63 const belowCellBaseIndex = (cellIndex + gridSize) * 4;
64 union(baseIndex + 2, belowCellBaseIndex);
65 }
66
67 // Connect right triangle of current cell with left triangle of cell to the right
68 if (col < gridSize - 1) {
69 const rightCellBaseIndex = (cellIndex + 1) * 4;
70 union(baseIndex + 1, rightCellBaseIndex + 3);
71 }
72
73 // Handle internal connections based on slash type
74 const currentChar = grid[row][col];
75
76 if (currentChar === '/') {
77 // Forward slash connects top-left and bottom-right
78 union(baseIndex, baseIndex + 3); // Connect top and left triangles
79 union(baseIndex + 1, baseIndex + 2); // Connect right and bottom triangles
80 } else if (currentChar === '\\') {
81 // Backslash connects top-right and bottom-left
82 union(baseIndex, baseIndex + 1); // Connect top and right triangles
83 union(baseIndex + 2, baseIndex + 3); // Connect bottom and left triangles
84 } else {
85 // Empty space - connect all 4 triangles
86 union(baseIndex, baseIndex + 1); // Connect top and right
87 union(baseIndex + 1, baseIndex + 2); // Connect right and bottom
88 union(baseIndex + 2, baseIndex + 3); // Connect bottom and left
89 }
90 }
91 }
92
93 return regionCount;
94}
95
Time and Space Complexity
Time Complexity: O(nΒ² Γ Ξ±(nΒ²))
The algorithm processes each cell in the n Γ n
grid exactly once. For each cell, it performs a constant number of union operations (at most 4 unions per cell). Each union operation involves two find operations, and each find operation has an amortized time complexity of Ξ±(m)
where Ξ±
is the inverse Ackermann function and m
is the total number of elements. Since we have 4nΒ²
total elements (4 triangles per cell), the find operation takes O(Ξ±(4nΒ²)) = O(Ξ±(nΒ²))
amortized time. Therefore, the overall time complexity is O(nΒ² Γ Ξ±(nΒ²))
, which is nearly linear in practice since Ξ±(n)
grows extremely slowly.
Space Complexity: O(nΒ²)
The algorithm uses a parent array p
of size 4nΒ²
to implement the Union-Find data structure, where each cell is divided into 4 triangular regions. This requires O(4nΒ²) = O(nΒ²)
space. The recursion stack for the find operation with path compression can go up to O(log(nΒ²)) = O(log n)
in the worst case before path compression optimizes it. Since O(nΒ²) > O(log n)
, the overall space complexity is O(nΒ²)
.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Incorrect Triangle Numbering/Mapping
One of the most common mistakes is incorrectly mapping the triangle positions within each cell. The triangles are numbered 0-3 representing top, right, bottom, and left respectively. Getting this mapping wrong will lead to incorrect connections between adjacent cells.
Pitfall Example:
# Wrong: Confusing which triangle connects to which neighbor if row_idx < grid_size - 1: # Incorrectly connecting top triangle with bottom neighbor union(4 * cell_base_idx + 0, (cell_base_idx + grid_size) * 4 + 2)
Solution: Always visualize the cell division clearly:
0 (top) /|\ / | \ 3 | 1 (left) (right) \ | / \|/ 2 (bottom)
- Bottom triangle (2) of current cell connects to top triangle (0) of cell below
- Right triangle (1) of current cell connects to left triangle (3) of right neighbor
2. Forgetting Path Compression in Find Operation
Without path compression, the find operation can degrade to O(n) time complexity in worst case, making the overall solution inefficient.
Pitfall Example:
def find(node: int) -> int:
# Missing path compression - inefficient!
while parent[node] != node:
node = parent[node]
return node
Solution: Always implement path compression:
def find(node: int) -> int:
if parent[node] != node:
parent[node] = find(parent[node]) # Path compression
return parent[node]
3. Incorrect Slash Character Connections
Misunderstanding which triangles should be connected for each slash type is a critical error.
Pitfall Example:
if slash_char == '/': # Wrong connections for '/' union(4 * cell_base_idx + 0, 4 * cell_base_idx + 2) # Top with bottom (incorrect!) union(4 * cell_base_idx + 1, 4 * cell_base_idx + 3) # Right with left (incorrect!)
Solution: Remember the visual representation:
/
divides the cell diagonally from bottom-left to top-right:- Connects top (0) with left (3)
- Connects right (1) with bottom (2)
\
divides the cell diagonally from top-left to bottom-right:- Connects top (0) with right (1)
- Connects left (3) with bottom (2)
4. Off-by-One Errors in Boundary Checks
Forgetting to check boundaries before connecting to adjacent cells will cause index out of bounds errors.
Pitfall Example:
# Missing boundary check - will fail at grid edges union(4 * cell_base_idx + 2, (cell_base_idx + grid_size) * 4 + 0) union(4 * cell_base_idx + 1, (cell_base_idx + 1) * 4 + 3)
Solution: Always check boundaries before connecting to neighbors:
if row_idx < grid_size - 1: # Not at bottom edge union(4 * cell_base_idx + 2, (cell_base_idx + grid_size) * 4 + 0) if col_idx < grid_size - 1: # Not at right edge union(4 * cell_base_idx + 1, (cell_base_idx + 1) * 4 + 3)
5. Incorrect Initial Component Count
Starting with the wrong number of components will give an incorrect final answer.
Pitfall Example:
# Wrong: Only counting cells, not triangular regions region_count = grid_size * grid_size # Should be multiplied by 4!
Solution: Each cell is divided into 4 triangular regions:
region_count = grid_size * grid_size * 4
How many times is a tree node visited in a depth first search?
Recommended Readings
https assets algo monster cover_photos dfs svg Depth First Search Prereqs Recursion Review problems recursion_intro Trees problems tree_intro With a solid understanding of recursion under our belts we are now ready to tackle one of the most useful techniques in coding interviews Depth First Search DFS As the name suggests
https assets algo monster cover_photos bfs svg Breadth First Search on Trees Hopefully by this time you've drunk enough DFS Kool Aid to understand its immense power and seen enough visualization to create a call stack in your mind Now let me introduce the companion spell Breadth First Search BFS
Union Find Disjoint Set Union Data Structure Introduction Prerequisite Depth First Search Review problems dfs_intro Once we have a strong grasp of recursion and Depth First Search we can now introduce Disjoint Set Union DSU This data structure is motivated by the following problem Suppose we have sets of elements
Want a Structured Path to Master System Design Too? Donβt Miss This!