<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 Solution:
    def containsCycle(self, grid: List[List[str]]) -> bool:
        # #APPROACH 1: DEPTH FIRST SEARCH -> SEE IF YOU CAN COME ACROSS THE SAME ELEMENT
        # # KEY IS TO TRACK PREVIOUS ELEMENT
        # # if next node is visited return true
        # # if next node is not in grid return false. 
        # # MAKE SURE NEXT NODE IS NOT PREVIOUS NODE
        # # for one node return true if atleast one of the nodes returns true 
        # def dfs(i, j, visited, value, prev): 
        #     if i <0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] != value: 
        #         return False
        #     # GO IN NEW DIRECTION, NOT BACKWARDS
        #     if prev and prev == (i,j): 
        #         return False
        #     if (i, j) in visited: 
        #         return True
        #     visited.add((i, j))
        #     return dfs(i+1, j, visited, value, (i, j)) or dfs(i, j+1 , visited, value, (i, j)) or dfs(i, j-1, visited, value,(i, j)) or dfs(i-1,j,  visited, value, (i,j)) 
        # for r in range(len(grid)): 
        #     for c in range(len(grid[0])): 
        #         if dfs(r, c, set(), grid[r][c], None): 
        #             return True
        # return False
        m = len(grid)
        n = len(grid[0])
        uf = UnionFind(m,n)
        for i in range(m): 
            for j in range(n):
                neighbors = [(i+1,j), (i, j+1)]
                for r, c in neighbors: 
                    if 0<=r<m and 0<=c<n and grid[r][c] == grid[i][j]: 
                        if not uf.union(i*n+j, r*n+c): 
                            return True
     

class UnionFind: 
    def __init__(self, m, n): 
        self.parent = list(range(m*n))
        self.rank = [1] * m*n
    
    def find(self, x): 
        if self.parent[x] != x: 
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]
    
    def union(self,x, y): 
        parent_x = self.find(x)
        parent_y = self.find(y)
        if parent_x == parent_y: 
            # already connected so no need to connect
            return False
        if self.rank[parent_x] > self.rank[parent_y]: 
            parent_x, parent_y = parent_y, parent_x

        self.parent[parent_x] = parent_y
        self.rank[parent_y] += self.rank[parent_x]
        return True


        
35339