1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| class Solution { private final int[][] DIRECTIONS = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
public boolean containsCycle(char[][] grid) { for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] >= 97 && hasCycle(grid, i, j, -1, -1)) { return true; } } } return false; }
private boolean hasCycle(char[][] grid, int row, int col, int prevRow, int prevCol) { char currChar = grid[row][col]; grid[row][col] -= 32; for (int[] direction : DIRECTIONS) { int newRow = row + direction[0]; int newCol = col + direction[1]; if (!isOutBound(grid, newRow, newCol) && (newRow != prevRow || newCol != prevCol) && Character.toLowerCase(grid[newRow][newCol]) == currChar) { if (grid[newRow][newCol] != currChar) { return true; } else if (hasCycle(grid, newRow, newCol, row, col)) { return true; } } } return false; }
private boolean isOutBound(char[][] grid, int row, int col) { return row < 0 || row >= grid.length || col < 0 || col >= grid[0].length; } }
|