|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | + |
| 4 | +public class BJ_1941_소문난_칠공주 { |
| 5 | + |
| 6 | + private static final int N = 5; |
| 7 | + private static final int SIZE = 25; |
| 8 | + private static final int[] dx = { -1, 1, 0, 0 }; |
| 9 | + private static final int[] dy = { 0, 0, -1, 1 }; |
| 10 | + |
| 11 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 12 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 13 | + |
| 14 | + private static int ans; |
| 15 | + private static boolean[] visited; |
| 16 | + private static boolean[][] isS; |
| 17 | + |
| 18 | + public static void main(String[] args) throws IOException { |
| 19 | + init(); |
| 20 | + sol(); |
| 21 | + } |
| 22 | + |
| 23 | + private static void init() throws IOException { |
| 24 | + isS = new boolean[N][N]; |
| 25 | + for (int i = 0; i < N; i++) { |
| 26 | + String line = br.readLine(); |
| 27 | + for (int j = 0; j < N; j++) { |
| 28 | + isS[i][j] = line.charAt(j) == 'S'; |
| 29 | + } |
| 30 | + } |
| 31 | + visited = new boolean[1 << SIZE]; |
| 32 | + } |
| 33 | + |
| 34 | + private static void sol() throws IOException { |
| 35 | + for (int i = 0; i < SIZE; i++) { |
| 36 | + if (!isS[i / N][i % N]) continue; |
| 37 | + |
| 38 | + int mask = 1 << i; |
| 39 | + |
| 40 | + visited[mask] = true; |
| 41 | + dfs(1, 1, mask); |
| 42 | + } |
| 43 | + |
| 44 | + bw.write(ans + ""); |
| 45 | + bw.flush(); |
| 46 | + bw.close(); |
| 47 | + br.close(); |
| 48 | + } |
| 49 | + |
| 50 | + private static void dfs(int depth, int sCount, int mask) { |
| 51 | + if (7 - depth + sCount < 4) return; |
| 52 | + |
| 53 | + if (depth == 7) { |
| 54 | + ans++; |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + for (int i = 0; i < SIZE; i++) { |
| 59 | + if ((mask & (1 << i)) == 0) continue; |
| 60 | + |
| 61 | + int x = i / N; |
| 62 | + int y = i % N; |
| 63 | + |
| 64 | + for (int d = 0; d < 4; d++) { |
| 65 | + int nx = x + dx[d]; |
| 66 | + int ny = y + dy[d]; |
| 67 | + |
| 68 | + if (OOB(nx, ny)) continue; |
| 69 | + |
| 70 | + int next = nx * N + ny; |
| 71 | + int nextMask = mask | (1 << next); |
| 72 | + |
| 73 | + if ((mask & (1 << next)) != 0) continue; |
| 74 | + if (visited[nextMask]) continue; |
| 75 | + |
| 76 | + visited[nextMask] = true; |
| 77 | + dfs(depth + 1, sCount + (isS[nx][ny] ? 1 : 0), nextMask); |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + private static boolean OOB(int x, int y) { |
| 83 | + return x < 0 || N <= x || y < 0 || N <= y; |
| 84 | + } |
| 85 | + |
| 86 | +} |
| 87 | +``` |
0 commit comments