Sunday, March 13, 2022

Graphs - Level line wise traversal

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
2

O/P:
Level: 0 --> 2 
Level: 1 --> 1 3 
Level: 2 --> 0  cycle 4 
Level: 3 --> 5 6 
Level: 4 -->  cycle 


Using this we can detect the number of cycle, with the level order line wise traversal



1. Remove
2, Mark
3. Work
4, Add child


package pep.Day40;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Queue;

public class Graphs_Level_Order_Traversal {

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());
Queue<Integer> queue = new ArrayDeque<>();
queue.add(src);
boolean[] visited = new boolean[vtces];
int level = 0;
while (!queue.isEmpty()) {
int size = queue.size();
System.out.print("Level: " + level + " --> ");
for (int i = 0; i < size; i++) {
int out = queue.remove();        // REMOVE
if (visited[out]) {
System.out.print("cycle");
continue;
}
visited[out] = true;            // MARK
System.out.print(out + " ");    // WORK
for (Edge e : graph[out]) {     // Add CHILD
if (!visited[e.nbr])
queue.add(e.nbr);
}

}
System.out.println();
level++;
}


}

}







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:...