diff --git a/g0rnn/README.md b/g0rnn/README.md index 1190141..584ca25 100644 --- a/g0rnn/README.md +++ b/g0rnn/README.md @@ -30,4 +30,5 @@ | 26차시 | 2025.05.26 | 구현 | [서버 증설 횟수](https://school.programmers.co.kr/learn/courses/30/lessons/389479?language=java) | https://github.com/AlgoLeadMe/AlgoLeadMe-12/pull/106 | | 27차시 | 2025.06.15 | Floyd-Warshall | [케빈 베이컨의 6단계 법칙](https://www.acmicpc.net/problem/1389) | https://github.com/AlgoLeadMe/AlgoLeadMe-12/pull/113 | | 28차시 | 2025.06.27 | BFS | [상어 중학교](https://www.acmicpc.net/problem/21609) | https://github.com/AlgoLeadMe/AlgoLeadMe-12/pull/115 | +| 29차시 | 2025.07.22 | combination | [소문난 칠공주](https://www.acmicpc.net/problem/1941) | https://github.com/AlgoLeadMe/AlgoLeadMe-12/pull/119 | --- diff --git a/g0rnn/combination/29-g0rnn.java b/g0rnn/combination/29-g0rnn.java new file mode 100644 index 0000000..9393ea0 --- /dev/null +++ b/g0rnn/combination/29-g0rnn.java @@ -0,0 +1,72 @@ +package beakjoon; + +import java.util.*; +import java.io.*; + +public class Sol1941 { + + static int ans = 0; + static char[][] board = new char[5][5]; + static int[][] offset = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; + static List selected = new ArrayList<>(); + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + for (int i = 0; i < 5; i++) { + board[i] = br.readLine().toCharArray(); + } + br.close(); + + comb(0, 0); + System.out.println(ans); + } + + // 조합을 만들고 뽑은 칸이 연속적이면서 & S가 4개 이상인지 확인 + private static void comb(int start, int depth) { + if (depth == 7) { + if (isValid()) { + ans++; + } + return; + } + + for (int i = start; i < 25; i++) { + selected.add(i); + comb(i + 1, depth + 1); + selected.remove(selected.size() - 1); + } + } + + private static boolean isValid() { + int cntS = 0; + boolean[] check = new boolean[25]; + Queue q = new ArrayDeque<>(); + q.offer(selected.get(0)); + check[selected.get(0)] = true; + + int countVisited = 1; // 방문한 칸의 수 + if (board[selected.get(0) / 5][selected.get(0) % 5] == 'S') cntS++; + + while (!q.isEmpty()) { + int now = q.poll(); + int x = now % 5; + int y = now / 5; + + for (int[] o : offset) { + int nx = x + o[0]; + int ny = y + o[1]; + int next = ny * 5 + nx; + + if (nx < 0 || nx >= 5 || ny < 0 || ny >= 5) continue; + if (!selected.contains(next)) continue; // 내가 선택한 칸만 이동하도록 + if (check[next]) continue; + + check[next] = true; + q.offer(next); + countVisited++; + if (board[ny][nx] == 'S') cntS++; + } + } + return countVisited == 7 && cntS >= 4; + } +}