|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + |
| 7 | + static char[][] map = new char[5][5]; |
| 8 | + static int[] selected = new int[7]; |
| 9 | + static int ans = 0; |
| 10 | + static int[] dr = {-1, 1, 0, 0}; |
| 11 | + static int[] dc = {0, 0, -1, 1}; |
| 12 | + |
| 13 | + public static void main(String[] args) throws IOException { |
| 14 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 15 | + for (int i = 0; i < 5; i++) { |
| 16 | + map[i] = br.readLine().toCharArray(); |
| 17 | + } |
| 18 | + |
| 19 | + combination(0, 0, 0); |
| 20 | + System.out.println(ans); |
| 21 | + } |
| 22 | + |
| 23 | + static void combination(int idx, int cnt, int sCnt) { |
| 24 | + if (cnt - sCnt > 3) return; |
| 25 | + |
| 26 | + if (cnt == 7) { |
| 27 | + if (sCnt >= 4) { |
| 28 | + if (isConnected()) ans++; |
| 29 | + } |
| 30 | + return; |
| 31 | + } |
| 32 | + |
| 33 | + if (idx == 25) return; |
| 34 | + |
| 35 | + selected[cnt] = idx; |
| 36 | + combination(idx + 1, cnt + 1, sCnt + (map[idx / 5][idx % 5] == 'S' ? 1 : 0)); |
| 37 | + |
| 38 | + combination(idx + 1, cnt, sCnt); |
| 39 | + } |
| 40 | + |
| 41 | + static boolean isConnected() { |
| 42 | + boolean[] visited = new boolean[7]; |
| 43 | + Deque<Integer> q = new ArrayDeque<>(); |
| 44 | + |
| 45 | + q.add(0); |
| 46 | + visited[0] = true; |
| 47 | + int count = 1; |
| 48 | + |
| 49 | + while (!q.isEmpty()) { |
| 50 | + int curIdx = q.poll(); |
| 51 | + int r = selected[curIdx] / 5; |
| 52 | + int c = selected[curIdx] % 5; |
| 53 | + |
| 54 | + for (int i = 0; i < 4; i++) { |
| 55 | + int nr = r + dr[i]; |
| 56 | + int nc = c + dc[i]; |
| 57 | + |
| 58 | + for (int next = 0; next < 7; next++) { |
| 59 | + if (!visited[next] && selected[next] / 5 == nr && selected[next] % 5 == nc) { |
| 60 | + visited[next] = true; |
| 61 | + count++; |
| 62 | + q.add(next); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + return count == 7; |
| 68 | + } |
| 69 | +} |
| 70 | +``` |
0 commit comments