Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- public class lab1Task4 {
- BufferedReader br;
- StringTokenizer in;
- PrintWriter out;
- public static int numberOfVerticles;
- public static int numberOfEdges;
- public int[][] edges;
- public int[][] adjacencyMatrix;
- public boolean[] isUsed;
- public int[] whichComponent;
- public int currentComponent;
- public static void main(String[] args) {
- new lab1Task4().run();
- }
- public void solve() throws IOException {
- readInputFile();
- fillAdjacencyMatrix();
- findComponents();
- fillOutputFile();
- }
- public void fillAdjacencyMatrix() {
- adjacencyMatrix = new int[numberOfVerticles][numberOfVerticles];
- for (int i = 0; i < numberOfEdges; i++) {
- adjacencyMatrix[edges[i][0] - 1][edges[i][1] - 1] = 1;
- adjacencyMatrix[edges[i][1] - 1][edges[i][0] - 1] = 1;
- }
- }
- public void findComponents() {
- whichComponent = new int[numberOfVerticles];
- currentComponent = 1;
- for(int i = 0; i < numberOfVerticles; i++) {
- if(!isUsed[i]) {
- whichComponent[i] = currentComponent;
- depthFirstSearch(i);
- currentComponent++;
- }
- }
- }
- public void depthFirstSearch(int currentVertilce) {
- isUsed[currentVertilce] = true;
- for (int i = 0; i < numberOfVerticles; i++)
- if (adjacencyMatrix[currentVertilce][i] == 1) {
- int nextVerticle = i;
- whichComponent[nextVerticle] = currentComponent;
- if (!isUsed[nextVerticle])
- depthFirstSearch(nextVerticle);
- }
- }
- public void readInputFile() throws IOException {
- br = new BufferedReader(new FileReader("input.txt"));
- numberOfVerticles = Integer.parseInt(nextToken());
- numberOfEdges = Integer.parseInt(nextToken());
- edges = new int[numberOfEdges][2];
- isUsed = new boolean[numberOfVerticles];
- for (int i = 0; i < numberOfEdges; i++) {
- edges[i][0] = Integer.parseInt(nextToken());
- edges[i][1] = Integer.parseInt(nextToken());
- }
- }
- public void fillOutputFile() throws IOException {
- out = new PrintWriter("output.txt");
- out.println(currentComponent - 1);
- for(int i = 0; i < numberOfVerticles; i++)
- out.print(whichComponent[i] + " ");
- out.close();
- }
- public void run() {
- try {
- solve();
- } catch (IOException e) {
- e.printStackTrace();
- System.exit(1);
- }
- }
- public String nextToken() throws IOException {
- while (in == null || !in.hasMoreTokens()) {
- in = new StringTokenizer(br.readLine());
- }
- return in.nextToken();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement