Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid.
A cycle is a path of length 4 or more 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
same value of the current cell.
Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell.
Return true if any cycle of the same value exists in grid, otherwise, return false.
****
Input: grid =[["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]Output: trueExplanation: There are two valid cycles shown in different colors in the image below:
****
Input: grid =[["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]Output: trueExplanation: There is only one valid cycle highlighted in the image below:
A cycle exists if we can revisit a cell (with the same character) that is not the immediate parent in the DFS path. We use DFS to traverse the grid, marking visited cells, and track the previous cell to avoid trivial backtracking.
classSolution {
public:int m, n;
vector<vector<bool>> vis;
booldfs(vector<vector<char>>& grid, int x, int y, int px, int py, char ch) {
vis[x][y] = true;
int dirs[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
for (auto& d : dirs) {
int nx = x + d[0], ny = y + d[1];
if (nx == px && ny == py) continue;
if (nx >=0&& nx < m && ny >=0&& ny < n && grid[nx][ny] == ch) {
if (vis[nx][ny]) return true;
if (dfs(grid, nx, ny, x, y, ch)) return true;
}
}
return false;
}
boolcontainsCycle(vector<vector<char>>& grid) {
m = grid.size(); n = grid[0].size();
vis = vector<vector<bool>>(m, vector<bool>(n, false));
for (int i =0; i < m; ++i) {
for (int j =0; j < n; ++j) {
if (!vis[i][j]) {
if (dfs(grid, i, j, -1, -1, grid[i][j])) return true;
}
}
}
return false;
}
};
classSolution {
int m, n;
boolean[][] vis;
int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};
booleandfs(char[][] grid, int x, int y, int px, int py, char ch) {
vis[x][y]=true;
for (int[] d : dirs) {
int nx = x + d[0], ny = y + d[1];
if (nx == px && ny == py) continue;
if (nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny]== ch) {
if (vis[nx][ny]) returntrue;
if (dfs(grid, nx, ny, x, y, ch)) returntrue;
}
}
returnfalse;
}
publicbooleancontainsCycle(char[][] grid) {
m = grid.length; n = grid[0].length;
vis =newboolean[m][n];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (!vis[i][j]) {
if (dfs(grid, i, j, -1, -1, grid[i][j])) returntrue;
}
}
}
returnfalse;
}
}
classSolution {
privateval dirs = arrayOf(intArrayOf(0,1), intArrayOf(1,0), intArrayOf(0,-1), intArrayOf(-1,0))
funcontainsCycle(grid: Array<CharArray>): Boolean {
val m = grid.size
val n = grid[0].size
val vis = Array(m) { BooleanArray(n) }
fundfs(x: Int, y: Int, px: Int, py: Int, ch: Char): Boolean {
vis[x][y] = truefor ((dx, dy) in dirs) {
val nx = x + dx
val ny = y + dy
if (nx == px && ny == py) continueif (nx in0 until m && ny in0 until n && grid[nx][ny] == ch) {
if (vis[nx][ny]) returntrueif (dfs(nx, ny, x, y, ch)) returntrue }
}
returnfalse }
for (i in0 until m) {
for (j in0 until n) {
if (!vis[i][j]) {
if (dfs(i, j, -1, -1, grid[i][j])) returntrue }
}
}
returnfalse }
}
classSolution:
defcontainsCycle(self, grid: list[list[str]]) -> bool:
m, n = len(grid), len(grid[0])
vis = [[False]*n for _ in range(m)]
defdfs(x: int, y: int, px: int, py: int, ch: str) -> bool:
vis[x][y] =Truefor dx, dy in ((0,1),(1,0),(0,-1),(-1,0)):
nx, ny = x+dx, y+dy
if nx == px and ny == py:
continueif0<= nx < m and0<= ny < n and grid[nx][ny] == ch:
if vis[nx][ny]:
returnTrueif dfs(nx, ny, x, y, ch):
returnTruereturnFalsefor i in range(m):
for j in range(n):
ifnot vis[i][j]:
if dfs(i, j, -1, -1, grid[i][j]):
returnTruereturnFalse
impl Solution {
pubfncontains_cycle(grid: Vec<Vec<char>>) -> bool {
let m = grid.len();
let n = grid[0].len();
letmut vis =vec![vec![false; n]; m];
fndfs(grid: &Vec<Vec<char>>, vis: &mut Vec<Vec<bool>>, x: usize, y: usize, px: isize, py: isize, ch: char) -> bool {
vis[x][y] =true;
let dirs = [(0,1),(1,0),(0,-1),(-1,0)];
for (dx, dy) in dirs.iter() {
let nx = x asisize+ dx;
let ny = y asisize+ dy;
if nx == px && ny == py { continue; }
if nx >=0&& nx < vis.len() asisize&& ny >=0&& ny < vis[0].len() asisize {
let nxu = nx asusize;
let nyu = ny asusize;
if grid[nxu][nyu] == ch {
if vis[nxu][nyu] { returntrue; }
if dfs(grid, vis, nxu, nyu, x asisize, y asisize, ch) { returntrue; }
}
}
}
false }
for i in0..m {
for j in0..n {
if!vis[i][j] {
if dfs(&grid, &mut vis, i, j, -1, -1, grid[i][j]) {
returntrue;
}
}
}
}
false }
}