Pagini recente » Cod sursa (job #2224231) | Cod sursa (job #2235310) | Cod sursa (job #2955879) | Cod sursa (job #3253374) | Cod sursa (job #1239736)
import java.io.*;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Main {
static List<List<Integer>> G;
static int V;
static boolean[] Visited;
static void DFS(final int x) {
Visited[x] = true;
for (int y: G.get(x))
if (!Visited[y])
DFS(y);
}
static void addEdge(final int x, final int y) {
G.get(x).add(y);
G.get(y).add(x);
}
public static void main(String[] args) throws IOException {
Scanner reader = new Scanner(new FileInputStream("dfs.in"));
V = reader.nextInt();
G = new ArrayList<List<Integer>>(V);
int edgeCount = reader.nextInt();
for (; edgeCount > 0; --edgeCount) {
int x = reader.nextInt() - 1;
int y = reader.nextInt() - 1;
addEdge(x, y);
}
Visited = new boolean[V];
reader.close();
int componentCount = 0;
for (int x = 0; x < V; ++x) {
if (!Visited[x]) {
++componentCount;
DFS(x);
}
}
PrintWriter writer = new PrintWriter("dfs.out");
writer.write(componentCount + "\n");
writer.close();
}
}