|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + |
| 7 | + static char[][] map = new char[12][6]; |
| 8 | + static int[] dr = {-1, 1, 0, 0}; |
| 9 | + static int[] dc = {0, 0, -1, 1}; |
| 10 | + static boolean isPopped; |
| 11 | + |
| 12 | + public static void main(String[] args) throws IOException { |
| 13 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 14 | + for (int i = 0; i < 12; i++) { |
| 15 | + map[i] = br.readLine().toCharArray(); |
| 16 | + } |
| 17 | + |
| 18 | + int chainCount = 0; |
| 19 | + while (true) { |
| 20 | + isPopped = false; |
| 21 | + boolean[][] visited = new boolean[12][6]; |
| 22 | + |
| 23 | + for (int i = 0; i < 12; i++) { |
| 24 | + for (int j = 0; j < 6; j++) { |
| 25 | + if (map[i][j] != '.' && !visited[i][j]) { |
| 26 | + bfs(i, j, visited); |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + if (!isPopped) break; |
| 32 | + |
| 33 | + fall(); |
| 34 | + chainCount++; |
| 35 | + } |
| 36 | + |
| 37 | + System.out.println(chainCount); |
| 38 | + } |
| 39 | + |
| 40 | + static void bfs(int r, int c, boolean[][] visited) { |
| 41 | + List<int[]> puyos = new ArrayList<>(); |
| 42 | + Queue<int[]> q = new LinkedList<>(); |
| 43 | + char color = map[r][c]; |
| 44 | + |
| 45 | + q.add(new int[]{r, c}); |
| 46 | + puyos.add(new int[]{r, c}); |
| 47 | + visited[r][c] = true; |
| 48 | + |
| 49 | + while (!q.isEmpty()) { |
| 50 | + int[] cur = q.poll(); |
| 51 | + |
| 52 | + for (int i = 0; i < 4; i++) { |
| 53 | + int nr = cur[0] + dr[i]; |
| 54 | + int nc = cur[1] + dc[i]; |
| 55 | + |
| 56 | + if (nr >= 0 && nr < 12 && nc >= 0 && nc < 6) { |
| 57 | + if (!visited[nr][nc] && map[nr][nc] == color) { |
| 58 | + visited[nr][nc] = true; |
| 59 | + q.add(new int[]{nr, nc}); |
| 60 | + puyos.add(new int[]{nr, nc}); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + if (puyos.size() >= 4) { |
| 67 | + for (int[] p : puyos) { |
| 68 | + map[p[0]][p[1]] = '.'; |
| 69 | + } |
| 70 | + isPopped = true; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + static void fall() { |
| 75 | + for (int c = 0; c < 6; c++) { |
| 76 | + for (int r = 11; r > 0; r--) { |
| 77 | + if (map[r][c] == '.') { |
| 78 | + for (int k = r - 1; k >= 0; k--) { |
| 79 | + if (map[k][c] != '.') { |
| 80 | + map[r][c] = map[k][c]; |
| 81 | + map[k][c] = '.'; |
| 82 | + break; |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | +} |
| 90 | +``` |
0 commit comments