please see image for instructions starter code for Main.java import java.io.*; import java.util.*;; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(countConnectedComponents("data.txt")); } public static int countConnectedComponents(String fileName) { try { //the file to be opened for reading FileInputStream fis=new FileInputStream(fileName); Scanner sc=new Scanner(fis); //file to be scanned //returns true if there is another line to read ArrayList edge = new ArrayList(); Set set = new HashSet(); while(sc.hasNextLine()) { int temp [] = new int[2]; int index = 0; for(String s : sc.nextLine().split(" ")) { temp[index] = Integer.parseInt(s); set.add(s); index++; } edge.add(temp); } sc.close(); //closes the scanner int n = set.size(); int[] root = new int[n]; // initialize each node is an island for(int i=0; i
please see image for instructions
starter code for Main.java
import java.io.*;
import java.util.*;;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(countConnectedComponents("data.txt"));
}
public static int countConnectedComponents(String fileName)
{
try
{
//the file to be opened for reading
FileInputStream fis=new FileInputStream(fileName);
Scanner sc=new Scanner(fis); //file to be scanned
//returns true if there is another line to read
ArrayList<int []> edge = new ArrayList<int[]>();
Set<String> set = new HashSet<String>();
while(sc.hasNextLine())
{
int temp [] = new int[2];
int index = 0;
for(String s : sc.nextLine().split(" "))
{
temp[index] = Integer.parseInt(s);
set.add(s);
index++;
}
edge.add(temp);
}
sc.close(); //closes the scanner
int n = set.size();
int[] root = new int[n];
// initialize each node is an island
for(int i=0; i<n; i++){
root[i]=i;
}
int count = n;
for(int i = 0; i < edge.size(); i++)
{
int x = edge.get(i)[0];
int y = edge.get(i)[1];
int xRoot = root[x - 1];
int yRoot = root[y - 1];
if(xRoot!=yRoot){
count--;
root[xRoot]=yRoot;
}
}
return count;
}
catch(IOException e)
{
e.printStackTrace();
}
return 0;
}
}
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 2 images