BFS with parent
Time O(rows × cols) Space O(rows × cols)For each unvisited cell, BFS over same-letter neighbours storing each cell's parent. A visited same-letter neighbour that isn't the parent means a cycle.
import java.util.*;
class Solution {
public boolean containsCycle(char[][] grid) {
int m = grid.length, n = grid[0].length;
boolean[][] seen = new boolean[m][n];
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int sr = 0; sr < m; sr++)
for (int sc = 0; sc < n; sc++) {
if (seen[sr][sc]) continue;
seen[sr][sc] = true;
Deque<int[]> q = new ArrayDeque<>();
q.offer(new int[]{sr, sc, -1, -1}); // r, c, parent r, parent c
while (!q.isEmpty()) {
int[] t = q.poll();
for (int[] d : dirs) {
int r = t[0] + d[0], c = t[1] + d[1];
if (r < 0 || c < 0 || r >= m || c >= n || grid[r][c] != grid[sr][sc]) continue;
if (r == t[2] && c == t[3]) continue; // the edge we came along
if (seen[r][c]) return true;
seen[r][c] = true;
q.offer(new int[]{r, c, t[0], t[1]});
}
}
}
return false;
}
}Verdict: Iterative, so no deep recursion on 500 × 500 grids.