|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +public class Main { |
| 5 | + static int[] dr = {0, 0, -1, 1}; |
| 6 | + static int[] dc = {-1, 1, 0, 0}; |
| 7 | + static int answer; |
| 8 | + static char[][] arr; |
| 9 | + static int[] girls; |
| 10 | + public static void main(String[] args) { |
| 11 | + Scanner sc = new Scanner(System.in); |
| 12 | + arr = new char[5][5]; |
| 13 | + for (int i = 0; i < 5; i++) { |
| 14 | + arr[i] = sc.next().toCharArray(); |
| 15 | + } |
| 16 | + girls = new int[7]; |
| 17 | + solve(0, 0, 0); |
| 18 | + System.out.println(answer); |
| 19 | + sc.close(); |
| 20 | + } |
| 21 | + |
| 22 | + static void solve(int idx, int start, int sCount) { |
| 23 | + if (idx == 7) { |
| 24 | + if (sCount >= 4 && isValidGirls()) { answer++; } |
| 25 | + return; |
| 26 | + } |
| 27 | + |
| 28 | + for (int i = start; i < 25; i++) { |
| 29 | + int r = i / 5; |
| 30 | + int c = i % 5; |
| 31 | + |
| 32 | + girls[idx] = i; |
| 33 | + if (arr[r][c] == 'S') { |
| 34 | + solve(idx + 1, i + 1, sCount + 1); |
| 35 | + } else { |
| 36 | + solve(idx + 1, i + 1, sCount); |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + static boolean isValidGirls() { |
| 42 | + Queue<Integer> q = new ArrayDeque<>(); |
| 43 | + boolean[] visited = new boolean[25]; |
| 44 | + q.offer(girls[0]); |
| 45 | + visited[girls[0]] = true; |
| 46 | + while (!q.isEmpty()) { |
| 47 | + int x = q.poll(); |
| 48 | + int r = x / 5; |
| 49 | + int c = x % 5; |
| 50 | + for (int i = 0; i < 4; i++) { |
| 51 | + int nr = r + dr[i]; |
| 52 | + int nc = c + dc[i]; |
| 53 | + int y = nr * 5 + nc; |
| 54 | + if (nr < 0 || nr >= 5 || nc < 0 || nc >= 5) { continue; } |
| 55 | + if (visited[y]) { continue; } |
| 56 | + // girls에 포함된 경우에만 방문 표시 |
| 57 | + for (int idx = 0; idx < 7; idx++) { |
| 58 | + if (girls[idx] == y) { |
| 59 | + visited[y] = true; |
| 60 | + q.offer(y); |
| 61 | + break; |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + for (int girl : girls) { |
| 67 | + if (!visited[girl]) { return false;} |
| 68 | + } |
| 69 | + return true; |
| 70 | + |
| 71 | + } |
| 72 | +} |
| 73 | +``` |
0 commit comments