2
public boolean containsCycle(char[][] grid) {3
int rows = grid.length, cols = grid[0].length;5
// Create a boolean array of same dimensions to keep track of visited cells6
boolean[][] visited = new boolean[rows][cols];8
for (int i = 0; i < rows; i++) {9
for (int j = 0; j < cols; j++) {10
if (!visited[i][j] && dfs(grid, visited, i, j, 0, 0, grid[i][j])) {20
char[][] grid, boolean[][] visited, int i, int j, int prevI, int prevJ, char c) {21
// Check for out of bounds22
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return false;24
// Check whether the current char matches the previous char25
if (grid[i][j] != c) return false;27
// If we stumble upon the same cell, we're guaranteed to have found a cycle!32
// Mark the cell as visited35
// We want to search in the south direction ONLY IF we didn't come from north36
// Do the same for all four directions37
boolean south = i - prevI != -1;38
boolean north = i - prevI != 1;39
boolean east = j - prevJ != -1;40
boolean west = j - prevJ != 1;41
return (south && dfs(grid, visited, i + 1, j, i, j, c))42
|| (north && dfs(grid, visited, i - 1, j, i, j, c))43
|| (east && dfs(grid, visited, i, j + 1, i, j, c))44
|| (west && dfs(grid, visited, i, j - 1, i, j, c));