Problem 563648 · hard · Level 05 Advanced Algorithms & Graphs

Rooms Made by Diagonal Walls

union-find · grids · geometry modelling

A floor is made of square tiles described by grid, a list of equal-length strings. Each character is one tile:

  • / : a wall along the diagonal from the tile's bottom-left corner to its top-right corner
  • \ : a wall along the diagonal from the tile's top-left corner to its bottom-right corner
  • . : an empty tile with no wall

Walls are infinitely thin and the outer edge of the floor is not a wall. Return the number of separate regions the walls cut the floor into.

In Python source a backslash inside a string literal is written as two characters, so "/\\" is the two-tile row /\.

Examples

Input:  grid = ["/.", "./"]
Output: 3
Explanation: each wall cuts a corner triangle off the floor (top-left and bottom-right); the rest is one region.

Input:  grid = ["\\/", "/\\"]
Output: 4
Explanation: the rows are \/ and /\ : the two long diagonals cross in the middle and cut the floor into four triangles.

Input:  grid = ["..", ".."]
Output: 1

Constraints

  • 1 <= len(grid) <= 100, 1 <= len(grid[0]) <= 100, characters are /, \ or .
  • Target: O(R * C * alpha(R * C)) time.

Goals

  • Model each tile as four triangles so diagonals become union rules
  • Glue triangles across tile borders to count regions
  • Choose an indexing scheme that keeps the bookkeeping simple
Starting Python…