|
| 1 | +/** |
| 2 | + * 1559. Detect Cycles in 2D Grid |
| 3 | + * https://leetcode.com/problems/detect-cycles-in-2d-grid/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle |
| 7 | + * consisting of the same value in grid. |
| 8 | + * |
| 9 | + * A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From |
| 10 | + * a given cell, you can move to one of the cells adjacent to it - in one of the four directions |
| 11 | + * (up, down, left, or right), if it has the same value of the current cell. |
| 12 | + * |
| 13 | + * Also, you cannot move to the cell that you visited in your last move. For example, the cycle |
| 14 | + * (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last |
| 15 | + * visited cell. |
| 16 | + * |
| 17 | + * Return true if any cycle of the same value exists in grid, otherwise, return false. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {character[][]} grid |
| 22 | + * @return {boolean} |
| 23 | + */ |
| 24 | +var containsCycle = function(grid) { |
| 25 | + const rows = grid.length; |
| 26 | + const cols = grid[0].length; |
| 27 | + const visited = new Set(); |
| 28 | + |
| 29 | + for (let row = 0; row < rows; row++) { |
| 30 | + for (let col = 0; col < cols; col++) { |
| 31 | + if (!visited.has(`${row},${col}`)) { |
| 32 | + if (explorePath(row, col, -1, -1, grid[row][col])) return true; |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + return false; |
| 38 | + |
| 39 | + function explorePath(row, col, prevRow, prevCol, char) { |
| 40 | + const key = `${row},${col}`; |
| 41 | + if (visited.has(key)) return true; |
| 42 | + visited.add(key); |
| 43 | + |
| 44 | + const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; |
| 45 | + for (const [dx, dy] of directions) { |
| 46 | + const newRow = row + dx; |
| 47 | + const newCol = col + dy; |
| 48 | + |
| 49 | + if (newRow === prevRow && newCol === prevCol) continue; |
| 50 | + if (newRow < 0 || newRow >= rows || newCol < 0 || newCol >= cols) continue; |
| 51 | + if (grid[newRow][newCol] !== char) continue; |
| 52 | + |
| 53 | + if (explorePath(newRow, newCol, row, col, char)) return true; |
| 54 | + } |
| 55 | + |
| 56 | + return false; |
| 57 | + } |
| 58 | +}; |
0 commit comments