Regions Cut By Slashes

 

Disjoint Set Union (Graph)

Intuition

Let's shift our perspective and consider slashes as connectors rather than dividers. Imagine each cell as a graph with four vertices at its corners, with slashes acting as edges between these vertices. The following diagram illustrates this concept:

cell as a graph

In this paradigm, a slash can be represented as follows:

  • A / slash connects the top-right point of a cell to the bottom-left point.
  • A \ slash connects the top-left point to the bottom-right point.
  • An empty space doesn't add any new connections.

The edges of the grid form the boundaries of the graph, creating an initial region. As we connect vertices (slashes), cycles may form, indicating the creation of new regions within the graph. By tracking the total number of cycles formed while iterating over all slashes, we determine the final count of regions.

To manage connected components, we use a DSU (Disjoint Set Union) data structure. We start by connecting the boundary points as the first region. As we process each cell, we treat each slash as an edge and union the corresponding vertices. If a union operation reveals that the vertices already share the same parent, it indicates a cycle, prompting us to increment our counter.

Algorithm

Main method regionsBySlashes:

  • Initialize variables:
    • gridSize to the length of grid.
    • pointsPerSide to gridSize + 1.
    • totalPoints to pointsPerSide * pointsPerSide.
  • Create an array parentArray to represent the disjoint set, initialized with -1.
  • Loop over the each point:
    • If the point lies on the border, set its parent to 0.
  • Set parent[0] (top-left corner) to -1 to make it the root.
  • Initialize regionCount to 1, accounting for the border region.
  • Iterate through each cell (i, j) in the grid:
    • If it's a forward slash (/):
      • Calculate the topRight and bottomLeft indices.
      • Call union on these points and add the result to regionCount.
    • If it's a backslash (\\):
      • Calculate the topLeft and bottomRight indices.
      • Call union on these points and add the result to regionCount.
  • Return the final regionCount.

Helper method find:

  • Define a method find with parameters: parentArray and the node.
  • If parentArray[node] is equal to -1:
    • node does not have any parent. Return node.
  • Set parentArray[node] to the parent of parentArray[node] using the find method. Return parentArray[node].

Helper method union:

  • Define a method union with parameters: parentArray and nodes node1 and node2.
  • Set parent1 to parent2 to the parents of node1 and node2 respectively.
  • If parent1 is equal to parent2, return 1.
  • Set parentArray[parent2] to parent1.
  • Return 0.

Comments

Popular posts from this blog

LeetCode 3Sum

30. Substring with Concatenation of All Words

Lowest common ancestor in a binary Tree