<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:
        # use bfs and keep track of the direction that we got to each node from
        # if we see a node twice, then have a cycle

        def is_cycle_bfs(i, j) -> bool:
            """Use bfs starting from i,j to detect if there is a cycle in the 2d grid.
            Updates the global visited
            
            Returns: bool - if there is a cycle in the 2d grid
            """
            cur_char = grid[i][j]
            queue = deque()
            # Each item in the queue will have the coords as well as the previous coords
            # that way, we can tell 
            queue.append((i,j, -1, -1))
            visited.add((i,j))

            moves = [
                [0,1],
                [0,-1],
                [1,0],
                [-1,0],
            ]
            print("starting bfs")
            while queue:
                i, j, prev_i, prev_j = queue.popleft()
                print(i,j)
                for move in moves:
                    next_i = i + move[0]
                    next_j = j + move[1]
                    
                    # # Mark this node as visited, if we see it again then
                    # # we have a cycle
                    # visited[(i,j)] = 1

                    # Check if the adj node is part of the current node's island
                    if(
                        0 <= next_i < len(grid)
                        and 0 <= next_j < len(grid[0])
                        and grid[next_i][next_j] == cur_char
                    ):
                        # If the node has already been visited, then we have a cycle
                        # but make sure that we aren't looking at the position that we just came from
                        if prev_i == next_i and prev_j == next_j:
                            continue
                        
                        # check if we've already seen the item
                        if (next_i, next_j) in visited:
                            return True

                        # Otherwise, it isn't the parent and we haven't seen it before
                        # so add it to the queue
                        # and mark as visited
                        queue.append((next_i, next_j, i, j))
                        visited.add((next_i, next_j))

            return False


        visited = set()
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if (i, j) not in visited:
                    is_cycle = is_cycle_bfs(i, j)
                    if is_cycle:
                        return True
        return False
2047