1559. Detect Cycles in 2D Grid Medium
1/**
2 * [1559] Detect Cycles in 2D Grid
3 *
4 * 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.
5 * 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.
6 * 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.
7 * Return true if any cycle of the same value exists in grid, otherwise, return false.
8 *
9 * Example 1:
10 * <img alt="" src="https://assets.leetcode.com/uploads/2020/07/15/1.png" style="width: 231px; height: 152px;" />
11 *
12 * Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]
13 * Output: true
14 * Explanation: There are two valid cycles shown in different colors in the image below:
15 * <img alt="" src="https://assets.leetcode.com/uploads/2020/07/15/11.png" style="width: 225px; height: 163px;" />
16 *
17 * Example 2:
18 * <img alt="" src="https://assets.leetcode.com/uploads/2020/07/15/22.png" style="width: 236px; height: 154px;" />
19 *
20 * Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]
21 * Output: true
22 * Explanation: There is only one valid cycle highlighted in the image below:
23 * <img alt="" src="https://assets.leetcode.com/uploads/2020/07/15/2.png" style="width: 229px; height: 157px;" />
24 *
25 * Example 3:
26 * <img alt="" src="https://assets.leetcode.com/uploads/2020/07/15/3.png" style="width: 183px; height: 120px;" />
27 *
28 * Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]]
29 * Output: false
30 *
31 *
32 * Constraints:
33 *
34 * m == grid.length
35 * n == grid[i].length
36 * 1 <= m, n <= 500
37 * grid consists only of lowercase English letters.
38 *
39 */
40pub struct Solution {}
41
42// problem: https://leetcode.com/problems/detect-cycles-in-2d-grid/
43// discuss: https://leetcode.com/problems/detect-cycles-in-2d-grid/discuss/?currentPage=1&orderBy=most_votes&query=
44
45// submission codes start here
46
47impl Solution {
48 pub fn contains_cycle(grid: Vec<Vec<char>>) -> bool {
49 false
50 }
51}
52
53// submission codes end
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58
59 #[test]
60 fn test_1559() {
61 }
62}
63
Back
© 2025 bowen.ge All Rights Reserved.