Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

7-mong3 #26

Merged
merged 1 commit into from
Mar 18, 2024
Merged
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
61 changes: 61 additions & 0 deletions mong3125/DFS/BOJ13023.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class BOJ13023 {

static int N, M; // ์‚ฌ๋žŒ์˜ ์ˆ˜, ์นœ๊ตฌ ๊ด€๊ณ„ ์ˆ˜
static List<Integer>[] friends;
static boolean[] visited; // ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ์ธ์ง€
static boolean isExist = false;

public static void main(String[] args) throws IOException {
// ์ž…๋ ฅ
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());

N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
friends = new ArrayList[N];
for (int i = 0; i < N; i++) {
friends[i] = new ArrayList<>();
}
visited = new boolean[N+1];

// ์–‘๋ฐฉํ–ฅ ์นœ๊ตฌ๊ด€๊ณ„ ๋งบ์–ด์ฃผ๊ธฐ
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());

friends[a].add(b);
friends[b].add(a);
}

for (int i = 0; i < N; i++) {
dfs(i, 1);
if (isExist) break;
}

int answer = isExist ? 1 : 0;
System.out.println(answer);
}

public static void dfs(int personId, int depth) {
if (depth >= 5 || isExist) {
isExist = true;
return;
}

visited[personId] = true;
for (int i : friends[personId]) {
if (!visited[i]) {
dfs(i, depth + 1);
}
Comment on lines +53 to +57
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

visited ๋ฆฌ์ŠคํŠธ์™€ friends ๋ฆฌ์ŠคํŠธ๊ฐ€ ์ •ํ™•ํžˆ ์–ด๋–ค ์—ญํ• ์„ ํ•˜๋Š”์ง€ ์„ค๋ช…ํ•ด์ฃผ์‹œ๋ฉด ๊ฐ์‚ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

visited๋Š” DFS์—์„œ ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š๊ธฐ ์œ„ํ•ด์„œ ์‚ฌ์šฉํ•œ ๋ฐฐ์—ด์ด๋ฉฐ n๋ฒˆ์งธ ์š”์†Œ์˜ boolean ๊ฐ’์€ n๋ฒˆ์งธ ๋…ธ๋“œ์˜ ๋ฐฉ๋ฌธ์—ฌ๋ถ€๋ฅผ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค.

friends๋Š” ๊ทธ๋ž˜ํ”„์—์„œ ์—ฃ์ง€๋ฅผ ํ‘œํ˜„ํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉํ•˜์˜€์œผ๋ฉฐ ๋ฆฌ์ŠคํŠธ์˜ ๋ฐฐ์—ด๋กœ ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค. n๋ฒˆ์งธ ์š”์†Œ์˜ ๋ฆฌ์ŠคํŠธ๋Š” n๋ฒˆ์งธ ๋…ธ๋“œ์˜ ์—ฃ์ง€๋“ค์„ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค.

}
visited[personId] = false;
}
}