Problem Summary
Given a N × N grid of 1 × 1 squares, each square consists of a ‘/‘, ‘\’, or blank space. Find the number of regions.
Solution
First, we split every square into two parts: the upper part and the lower part, and build a new graph.
As the following image shows, there are three cases:
Square (i, j) is now two nodes a = (i × n + j) × 2 + 1 and b = a + 1.
If s[i][j] == ‘ ‘, then we connect a and b. Otherwise a and b shouldn’t be connected.
Then we need to connect square (i, j) with square (i + 1, j) and (i, j + 1).
Between (i, j) and (i + 1, j) : we only need to connect b to the upper part of (i + 1, j), which is a + 2 × n.
Between (i, j) and (i + 1, j) : we connect the right part of (i, j) and the left part of (i + 1, j).
After this, we can easily find the number of connected components of the new graph with union-find.
Code
|
|