publicintfind(int x){ return pre[x] == x ? x : (pre[x] = find(pre[x])); }
publicbooleanjoin(int x, int y){ int fx = find(x), fy = find(y); if (fx == fy) returntrue; pre[fx] = fy; returnfalse; }
publicbooleancontainsCycle(char[][] grid){ int n = grid.length, m = grid[0].length; for (int i = 0; i < n * m; i++) pre[i] = i; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i > 0 && grid[i][j] == grid[i - 1][j] && join(i * m + j, (i - 1) * m + j)) { returntrue; } if (j > 0 && grid[i][j] == grid[i][j - 1] && join(i * m + j, i * m + j - 1)) { returntrue; } } } returnfalse; } }