959. Regions Cut By Slashes #298
Unanswered
mah-shamim
asked this question in
Q&A
Replies: 1 comment
-
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.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Topics:
Array
,Hash Table
,Depth-First Search
,Breadth-First Search
,Union Find
,Matrix
An
n x n
grid is composed of1 x 1
squares where each1 x 1
square consists of a'/'
,'\'
, or blank space' '
. These characters divide the square into contiguous regions.Given the grid
grid
represented as a string array, return the number of regions.Note that backslash characters are escaped, so a
'\'
is represented as'\\'
.Example 1:
Example 2:
Example 3:
Constraints:
n == grid.length == grid[i].length
1 <= n <= 30
grid[i][j]
is either'/'
,'\'
, or' '
.Beta Was this translation helpful? Give feedback.
All reactions