959. Regions Cut By Slashes #298
-
Topics: An Given the grid Note that backslash characters are escaped, so a Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
we can represent each Step-by-Step Approach:
Let's implement this solution in PHP: 959. Regions Cut By Slashes <?php
class UnionFind {
private $parent;
public function __construct($n) {
$this->parent = range(0, $n - 1);
}
public function find($x) {
if ($this->parent[$x] != $x) {
$this->parent[$x] = $this->find($this->parent[$x]);
}
return $this->parent[$x];
}
public function union($x, $y) {
$rootX = $this->find($x);
$rootY = $this->find($y);
if ($rootX != $rootY) {
$this->parent[$rootX] = $rootY;
}
}
}
function regionsBySlashes($grid) {
$n = count($grid);
$uf = new UnionFind($n * $n * 4);
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n; $j++) {
$root = 4 * ($i * $n + $j);
$char = $grid[$i][$j];
// Connect the parts within the cell
if ($char == ' ') {
$uf->union($root, $root + 1);
$uf->union($root + 1, $root + 2);
$uf->union($root + 2, $root + 3);
} elseif ($char == '/') {
$uf->union($root, $root + 3);
$uf->union($root + 1, $root + 2);
} elseif ($char == '\\') {
$uf->union($root, $root + 1);
$uf->union($root + 2, $root + 3);
}
// Connect with the right cell
if ($j + 1 < $n) {
$uf->union($root + 1, 4 * ($i * $n + $j + 1) + 3);
}
// Connect with the bottom cell
if ($i + 1 < $n) {
$uf->union($root + 2, 4 * (($i + 1) * $n + $j));
}
}
}
$regions = 0;
for ($i = 0; $i < $n * $n * 4; $i++) {
if ($uf->find($i) == $i) {
$regions++;
}
}
return $regions;
}
// Test cases
$grid1 = [" /", "/ "];
$grid2 = [" /", " "];
$grid3 = ["/\\", "\\/"];
echo regionsBySlashes($grid1); // Output: 2
echo regionsBySlashes($grid2); // Output: 1
echo regionsBySlashes($grid3); // Output: 5
?> Explanation:
This solution efficiently handles the problem within the given constraints. |
Beta Was this translation helpful? Give feedback.
we can represent each
1x1
square as 4 triangles, which allows us to apply a Union-Find (Disjoint Set Union, DSU) algorithm to count the distinct regions.Step-by-Step Approach:
Grid Representation:
1x1
square as 4 triangles:Mapping Characters:
' '
, all 4 triangles within it are connected.'/'
, the top-left triangle is connected to the bottom-right, and the top-right triangle is connected to the bottom-left.'\'
, the top-left triangle is connected to the top…