0% found this document useful (0 votes)
8 views2 pages

Message

Uploaded by

silpaganena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Message

Uploaded by

silpaganena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

//DO NOT EDIT ANYTHING IN SOLUTION CLASS

import java.util.*;
class Graph{ // Adjacency Matrix Implementation of an Undirected Graph
int adjmatrix[][], V, E;
Graph(int v){
this.V = v;
adjmatrix = new int[V+1][V+1];
}
void bfs(int v) // Breadth First Search implementation of AdjacencyMatrix
{
ArrayDeque <Integer>q = new ArrayDeque<>();
boolean vis[] = new boolean[V+1];
q.add(v); vis[v] = true;
int totalcost = 0;
while( !q.isEmpty() ){
int cur = q.poll();
System.out.print(cur + " ");
for(int d=0;d<=V;d++){
int cost = adjmatrix[cur][d];
if( cost != 0 && !vis[d] ){
q.add(d);
totalcost += cost;
vis[d] = true;
}
}
}
System.out.println("=> "+totalcost);
}
void dfs(int v){
boolean vis[] = new boolean[V+1];
int tc = dfs(vis, v);
System.out.println("=> " + tc);
}
int dfs(boolean vis[], int source){
vis[source] = true;
System.out.print(source + " ");
int tc = 0;
for(int dest=0;dest<=V;dest++){
int cost = adjmatrix[source][dest];
if( cost!=0 && !vis[dest] ){
tc += cost + dfs(vis, dest);
}
}
return tc;
}
void addEdge(int v1, int v2, int c){ // Inserts an edge from vertex v1 to v2
with cost(C)
this.adjmatrix[v1][v2] = c;
this.adjmatrix[v2][v1] = c;
this.E++;
}
void delEdge(int v1, int v2){ // Removes an edge from vertex v1 to v2
this.adjmatrix[v1][v2] = 0;
this.adjmatrix[v2][v1] = 0;
this.E--;
}
}
public class logic{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int v = sc.nextInt();// Vertices
Graph g = new Graph(v);
int n = sc.nextInt();// N number of commands
while(n-- != 0){
int c = sc.nextInt(); // Choice
switch(c){
case 1 -> g.addEdge(sc.nextInt(), sc.nextInt(), sc.nextInt());
case 2 -> g.delEdge(sc.nextInt(), sc.nextInt());
case 3 -> { System.out.print("BFS : "); g.bfs(sc.nextInt()); }
case 4 -> { System.out.print("DFS : "); g.dfs(sc.nextInt()); }
}
}
}
}

You might also like