Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions Seahee/week6/끝말잇기.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import java.util.HashSet;
import java.util.Set;

class Solution {
public int[] solution(int n, String[] words) {

Set<String> usedWord = new HashSet<>();
char lastAlpha = 0; // 이전 단어의 마지막 글자
int failedSeq = 0; // 몇 번째 단어에서 실패했는지

for (int i = 0; i < words.length; i++) {
String word = words[i];

// 이미 나온 단어인지 검사
if (usedWord.contains(word)) {
failedSeq = i + 1;
break;
}

// 이전 단어의 마지막 글자로 시작하는지 검사
if (i > 0 && lastAlpha != word.charAt(0)) { // 첫 번째 글자인 경우 제외 {
failedSeq = i + 1;
break;
}

usedWord.add(word);
lastAlpha = word.charAt(word.length() - 1);
}

if (failedSeq == 0) {
return new int[]{0, 0};
}

// failedSeq번째 단어를 말한 사람과 그 사람의 차례 계산
int person = failedSeq % n;
if (person == 0) person = n;

int turn = (failedSeq - 1) / n + 1; // 몇 번째 차례인지 (라운드)

return new int[]{person, turn};
}
}
77 changes: 77 additions & 0 deletions Seahee/week6/양과늑대.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
dfs 한 번 호출 시 O(N^2)
dfs 호출 수 O(2^N)
=> O(N^2 x 2^N)
*/

import java.util.ArrayList;
import java.util.List;

class Solution {

private List<Integer>[] children; // 각 노드의 자식 리스트
private int maxSheep = 0;

public int solution(int[] info, int[][] edges) {
int n = info.length;

// 자식 리스트 초기화
children = new ArrayList[n];
for (int i = 0; i < n; i++) {
children[i] = new ArrayList<>();
}

// 트리 구성 (부모 -> 자식)
for (int[] edge : edges) {
int parent = edge[0];
int child = edge[1];
children[parent].add(child);
}

int sheep = 1;
int wolf = 0;

// 처음에 갈 수 있는 후보 노드들 (루트의 자식들)
List<Integer> nextNodes = new ArrayList<>();
nextNodes.addAll(children[0]);

dfs(info, sheep, wolf, nextNodes);

return maxSheep;
}

private void dfs(int[] info, int sheep, int wolf, List<Integer> nextNodes) {
// 현재 상태에서 모은 양 수로 최대값 갱신
maxSheep = Math.max(maxSheep, sheep);

// 다음에 갈 수 있는 후보 노드들 중 하나를 선택해 보면서 완전 탐색
for (int i = 0; i < nextNodes.size(); i++) {
int node = nextNodes.get(i);

int nextSheep = sheep; //다음 dfs에서의 양, 늑대 수
int nextWolf = wolf;

// 현재 노드가 양인지 늑대인지에 따라 카운트 증가
if (info[node] == 0) {
nextSheep++;
} else {
nextWolf++;
}

// 늑대 수가 양 수 이상이면 이 경로는 더 진행 불가
if (nextWolf >= nextSheep) {
continue;
}

// 다음 후보 리스트 생성
// - 현재 선택한 노드는 후보에서 제거
// - 현재 노드의 자식들을 새 후보에 추가
List<Integer> newNextNodes = new ArrayList<>(nextNodes);
newNextNodes.remove(i); // 현재 방문한 노드는 후보에서 제거
newNextNodes.addAll(children[node]); // 자식들 추가

// 다음 상태로 DFS
dfs(info, nextSheep, nextWolf, newNextNodes);
}
}
}