• 문제 링크
5848번: Message Relay
Farmer John's N cows (1 <= N <= 1000) are conveniently numbered from 1..N. Using an old-fashioned communicating mechanism based on tin cans and strings, the cows have figured out how to communicate between each-other without Farmer John noticing. Each cow
www.acmicpc.net
• 풀이 과정
• 풀이 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Main {
static int[] graph;
static boolean[] visit;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
graph = new int[n];
for (int i = 0; i < n; i++)
graph[i] = Integer.parseInt(br.readLine()) - 1;
int cnt = 0;
for (int i = 0; i < n; i++) {
visit = new boolean[n];
if (!dfs(i)) cnt++;
}
bw.write(String.valueOf(cnt));
bw.flush();
}
private static boolean dfs(int node) {
if (graph[node] == -1) return false;
if (visit[node]) return true;
visit[node] = true;
return dfs(graph[node]);
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
public class Main {
static int[] graph;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
graph = new int[n];
for (int i = 0; i < n; i++)
graph[i] = Integer.parseInt(br.readLine()) - 1;
int cnt = 0;
while (n-- > 0) if (!bfs(n)) cnt++;
bw.write(String.valueOf(cnt));
bw.flush();
}
private static boolean bfs(int node) {
Queue<Integer> q = new LinkedList<>();
Set<Integer> set = new HashSet<>();
q.offer(node);
set.add(node);
while (!q.isEmpty()) {
int tgt = graph[q.poll()];
if (set.contains(tgt)) return true;
if (tgt == -1) return false;
q.offer(tgt);
set.add(tgt);
}
return false;
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 5958 Space Exploration - Graph Theory / Java (0) | 2023.07.07 |
---|---|
[백준] 10678 Meeting Time - Graph Theory / Java (0) | 2023.07.06 |
[백준] 5938 Daisy Chains in the Field - Graph Theory / Java (0) | 2023.07.04 |
[백준] 17199 Milk Factory - Graph Theory / Java (0) | 2023.07.03 |
[백준] 5966 Cow Cotillion - Data Structure / Java (0) | 2023.07.02 |
댓글