Code needs to be done in java, Basic coding please, still learning Program 2: Ma
ID: 3886137 • Letter: C
Question
Code needs to be done in java, Basic coding please, still learning
Program 2: Make a simple program that counts infected computers on a computer network. The virus spreads through the network, and every computer that is connected to an infected computer is infected. For example, there are seven computers and connected like the figure below. If computer #1 is infected, computer #3 and 6 will be infected through infection of computer #2 and 5. Computer #4 and 7 are safe. So, totally four computers are infected. Please implement your algorithm in Java but not use API. 6 Input In the first line, a number of computers is given and it's less than 100. The second line is a number of edges that represents a connection between two computers. After second line, each 1ine has two numbers that represent twoExplanation / Answer
import java.util.Scanner;
public class infectionGraph {
public static void main(String[] args)
{
int n,m,a,b,st;
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
int arr[][] = new int[n][n];
int inf[] = new int[n];;
int vis[] = new int[n];
for(int i=0;i<n;i++)
{
inf[i]=0;
vis[i]=0;
for(int j=0;j<n;j++)
{
arr[i][j]=0;
}
}
m = scan.nextInt();
for(int i=0;i<m;i++)
{
a = scan.nextInt();
b = scan.nextInt();
arr[a-1][b-1]=1;
arr[b-1][a-1]=1;
}
st = scan.nextInt();
int ans=0;
inf[0]=st-1;
int i = 0,len=1;
while(i<len)
{
if(vis[inf[i]]==1)
{
i++;
continue;
}
vis[inf[i]]=1;
ans++;
/*for(int k=0;k<len;k++)
{
System.out.print(inf[k]+" ");
}
System.out.println();
for(int k=0;k<n;k++)
{
System.out.print(vis[k]+" ");
}
System.out.println();*/
for(int j=0;j<n;j++)
{
if(arr[inf[i]][j]==1 && vis[j]==0)
{
inf[len]=j;
len++;
}
}
i++;
}
System.out.println(ans-1);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.