<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>

from collections import defaultdict
from itertools import product
from typing import List, Set, Tuple


class Graph:
    def __init__(self):
        self.adj = defaultdict(list)

    def add_edge(self, src: int, dst: int):
        self.adj[src].append(dst)


class LoopSearcher:
    def __init__(self, min_loop_size: int):
        self.min_loop_size = min_loop_size
        self.loop_found = False
        self.visited = defaultdict(int)

    def reset(self):
        self.loop_found = False
        self.visited = defaultdict(int)

    def dfs(self, graph: Graph, src: int, num_stepped: int):
        # print(f"-> {src} <-")
        self.visited[src] = num_stepped
        for child in graph.adj[src]:
            # print(f"\tChild {child}")
            if child in self.visited:
                loop_length = num_stepped - self.visited[child] + 1
                # print(f"\t\tVisited! Loop length = {loop_length}")
                if loop_length >= self.min_loop_size:
                    # print("\t\t\tHit!")
                    self.loop_found = True
            else:
                self.dfs(graph, child, num_stepped + 1)

    def search(self, graph: Graph, src: int) -> Tuple[bool, Set[int]]:
        self.reset()
        self.dfs(graph, src, 0)
        return self.loop_found, set(self.visited.keys())


class GridLoopSolver:
    def __init__(self, grid: List[List[str]], min_loop_size: int = 4):
        self.grid = grid
        self.min_loop_size = min_loop_size

        self.height = len(grid)
        self.width = len(grid[0])
        self.grid_idx = list(product(range(self.height), range(self.width)))
        self.offsets = [(-1, 0), (0, 1), (1, 0), (0, -1)]
        self.graph = self.create_graph()
        self.searcher = LoopSearcher(min_loop_size)

    def create_graph(self) -> Graph:
        graph = Graph()
        for r, c in self.grid_idx:
            # print(f"Cell: {(r, c)}")
            for r_friend, c_friend in self.find_adjacent_friends(r, c):
                # print(f"\tFriend: {(r_friend, c_friend)}")
                src = r * self.width + c
                dst = r_friend * self.width + c_friend
                graph.add_edge(src, dst)
        return graph

    def find_adjacent_friends(self, r: int, c: int) -> List[Tuple[int, int]]:
        friends = []
        for r_offset, c_offset in self.offsets:
            r_new = r + r_offset
            c_new = c + c_offset
            # print("Candidate:", (r_new, c_new))
            if (0 <= r_new < self.height) and (0 <= c_new < self.width):
                # print(r_new, c_new, self.grid[r][c], self.grid[r_new][c_new])
                if self.grid[r][c] == self.grid[r_new][c_new]:
                    friends.append((r_new, c_new))
        return friends

    def solve(self) -> bool:
        visited = set()
        nodes = list(self.graph.adj.keys())
        # print(dict(self.graph.adj))
        for node in nodes:
            if node not in visited:
                found_loop, node_path = self.searcher.search(self.graph, node)
                if found_loop:
                    print(node_path)
                    return True
                visited.update(node_path)
        return False


class Solution:
    def containsCycle(self, grid: List[List[str]]) -> bool:
        return GridLoopSolver(grid).solve()

2312