<p>Given a 2D array of characters <code>grid</code> of size <code>m x n</code>, you need to find if there exists any cycle consisting of the <strong>same value</strong> in <code>grid</code>.</p>

<p>A cycle is a path of <strong>length 4 or more</strong> in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the <strong>same value</strong> of the current cell.</p>

<p>Also, you cannot move to the cell that you visited in your last move. For example, the cycle <code>(1, 1) -&gt; (1, 2) -&gt; (1, 1)</code> is invalid because from <code>(1, 2)</code> we visited <code>(1, 1)</code> which was the last visited cell.</p>

<p>Return <code>true</code> if any cycle of the same value exists in <code>grid</code>, otherwise, return <code>false</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2020/07/15/1.png" style="width: 231px; height: 152px;" /></strong></p>

<pre>
<strong>Input:</strong> grid = [[&quot;a&quot;,&quot;a&quot;,&quot;a&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;a&quot;,&quot;a&quot;,&quot;a&quot;]]
<strong>Output:</strong> true
<strong>Explanation: </strong>There are two valid cycles shown in different colors in the image below:
<img alt="" src="https://assets.leetcode.com/uploads/2020/07/15/11.png" style="width: 225px; height: 163px;" />
</pre>

<p><strong class="example">Example 2:</strong></p>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2020/07/15/22.png" style="width: 236px; height: 154px;" /></strong></p>

<pre>
<strong>Input:</strong> grid = [[&quot;c&quot;,&quot;c&quot;,&quot;c&quot;,&quot;a&quot;],[&quot;c&quot;,&quot;d&quot;,&quot;c&quot;,&quot;c&quot;],[&quot;c&quot;,&quot;c&quot;,&quot;e&quot;,&quot;c&quot;],[&quot;f&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;]]
<strong>Output:</strong> true
<strong>Explanation: </strong>There is only one valid cycle highlighted in the image below:
<img alt="" src="https://assets.leetcode.com/uploads/2020/07/15/2.png" style="width: 229px; height: 157px;" />
</pre>

<p><strong class="example">Example 3:</strong></p>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2020/07/15/3.png" style="width: 183px; height: 120px;" /></strong></p>

<pre>
<strong>Input:</strong> grid = [[&quot;a&quot;,&quot;b&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;z&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;b&quot;,&quot;a&quot;]]
<strong>Output:</strong> false
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == grid.length</code></li>
	<li><code>n == grid[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 500</code></li>
	<li><code>grid</code> consists only of lowercase English letters.</li>
</ul>

class UnionFind:
    def __init__(self, size):
        self.parent = list(range(size))  # Each element is its own parent initially
        self.rank = [0] * size           # Initialize rank to 0 initially

    # Find operation with path compression
    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])  # Recursively find the root and compress the path
        return self.parent[x]

    # Union operation with union by rank
    def unite(self, x, y):
        x = self.find(x)  # Find the root of set x
        y = self.find(y)  # Find the root of set y

        if x == y:  # If both elements are in the same set, no need to union
            return False

        # Attach the shorter tree (lower rank) under the root of the taller tree
        if self.rank[x] < self.rank[y]:
            self.parent[x] = y  # Make y the parent of x
        elif self.rank[x] > self.rank[y]:
            self.parent[y] = x  # Make x the parent of y
        else:
            # If ranks are the same, arbitrarily choose one as the root and increment its rank
            self.parent[x] = y
            self.rank[y] += 1

        return True  # Union was successful


class Solution:
    def containsCycle(self, grid: List[List[str]]) -> bool:
        n = len(grid)       # Get the number of rows in the grid
        m = len(grid[0])    # Get the number of columns in the grid

        # Create an instance of DisjointSetUnion
        uf = UnionFind(n * m)  # Initialize Union-Find structure for all cells in the grid

        # Arrays to represent possible moves in the grid (right and down)
        dx = [0, 1]           # Movement in x direction (right)
        dy = [1, 0]           # Movement in y direction (down)

        # Loop through each cell in the grid
        for i in range(n):
            for j in range(m):
                # Check adjacent cells only in the right and down direction to avoid redundancy
                for k in range(2):
                    x = i + dx[k]  # Calculate new x coordinate
                    y = j + dy[k]  # Calculate new y coordinate

                    # Skip if out of bounds or values are different
                    if x < 0 or x >= n or y < 0 or y >= m or grid[i][j] != grid[x][y]:
                        continue

                    # Calculate indices for the current and adjacent cells
                    cur = i * m + j    # Linear index for current cell
                    next = x * m + y   # Linear index for adjacent cell

                    # If union is not successful, a cycle is found
                    if not uf.unite(cur, next):
                        return True    # Cycle found

        # No cycle found
        return False
            
30198