Tuesday, March 15, 2022

Spread Of Infection

I/P:
7 8 0 1 10 1 2 10 2 3 10 0 3 10 3 4 10 4 5 10 5 6 10 4 6 10 6 3

O/P: 4









package pep.Day42;

import java.io.*;
import java.util.*;

public class Spread_Of_Infection {

static class Edge {
int src;
int nbr;

Edge(int src, int nbr) {
this.src = src;
this.nbr = nbr;
}
}

public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int vtces = Integer.parseInt(br.readLine());
ArrayList<Edge>[] graph = new ArrayList[vtces];
for (int i = 0; i < vtces; i++) {
graph[i] = new ArrayList<>();
}

int edges = Integer.parseInt(br.readLine());
for (int i = 0; i < edges; i++) {
String[] parts = br.readLine().split(" ");
int v1 = Integer.parseInt(parts[0]);
int v2 = Integer.parseInt(parts[1]);
graph[v1].add(new Edge(v1, v2));
graph[v2].add(new Edge(v2, v1));
}

int src = Integer.parseInt(br.readLine());
int t = Integer.parseInt(br.readLine());

int[] visited = new int[vtces];
Arrays.fill(visited, -1);
System.out.println(getCount(graph, src, t, visited));

Arrays.fill(visited, 0);
System.out.println(getCount2(graph, src, t, visited));


}

private static int getCount2(ArrayList<Edge>[] graph, int src, int t, int[] visited) {
visited[src] = 1;
int count = 1;
Queue<Integer> queue = new LinkedList<>();
queue.add(src);
while (!queue.isEmpty()) {
int rem = queue.remove();

for (Edge e : graph[rem]) {
if (visited[e.nbr] == 0) {
visited[e.nbr] = visited[rem] + 1;

if (visited[e.nbr] > t)
return count;
count++;
queue.add(e.nbr);
}
}
}
return count;
}

public static int getCount(ArrayList<Edge>[] graph, int src, int time, int[] visited) {

int level = 1;
int count = 0;
Queue<Integer> queue = new ArrayDeque<>();
queue.add(src);


while (!queue.isEmpty()) {

int size = queue.size();
while (size-- > 0) {
if (level == time + 1)
return count;
int out = queue.remove();
if (visited[out] == -1) {
visited[out] = level;
count++;
}


for (Edge e : graph[out]) {
if (visited[e.nbr] == -1) {
queue.add(e.nbr);
}
}
}
level++;
}

return 0;
}

}





No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...