Question

In: Computer Science

Write a complete Java program which takes vertices and edges of an undirected graph from the...

Write a complete Java program which takes vertices and edges of an undirected graph from the input file input.txt (the graph as adjacency matrix) ,(adjacent vertics of every vertex ),(DFS traversal of the graph),(BFS traversal of the graph),(Graph is connected or not connected)

Solutions

Expert Solution

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Scanner;

class Operation{
    // declare global variables
    int Graph[][];
    int count,vertex, queue[],visited[];
    int front=0, rear=-1,row,col,m,n;
    //constructor
    Operation(String filename)  throws Exception{
        
        Scanner sc = new Scanner(new BufferedReader(new FileReader(filename)));
        // fetch no of  vertex
        //the first line of text file contains the number vertex
        if(sc.hasNextLine()){
            String[] line = sc.nextLine().trim().split(" ");
            vertex=Integer.parseInt(line[0]);
                        count=vertex;
        }
                
                Graph=new int[vertex][vertex];
                queue=new int[vertex];
                visited=new int[vertex];
        
        while(sc.hasNextLine()) {
                        String[] line = sc.nextLine().trim().split(" ");
                        m = Integer.parseInt(line[0]);
                        n = Integer.parseInt(line[1]);                          
                        Graph[m-1][n-1]=1;
                        Graph[n-1][m-1]=1;
        } 
                
                // print the adjacencymatrix
                System.out.println("\nAdjacency matrix of the graph:");
                for(int i=0;i<this.vertex;i++){
                        for(int j=0;j<this.vertex;j++){
                                System.out.print(Graph[i][j]+" ");
                        }
                        System.out.print("\n");
                }
    }
    
    // find dfs of a graph from given vertex
    // check also ifgraph is  connected or not
    // if DFS from a vertex visits all the vertices
    // thenit is connected
    void DFS(int v){
        int k;
                System.out.print((v+1)+"  ");
       //mark current vertex as visited
        visited[v]=1;
        count--;
        
        //check for each vertex
        for(k=0;k<vertex;k++){
           if(visited[k]==0 && Graph[v][k]==1){
                DFS(k);
                   }
                }
    }
 
        // do traversal using bfs
        void BFS(int v) {
                rear++;
                queue[rear] = v;
                while(front<=rear){
                        v=queue[front];
                        for(int i=0;i<vertex;i++){
                                if(Graph[v][i]==1  && visited[i]==0){
                                        rear++;
                                        queue[rear]=i;
                                        visited[i]=1;
                                }
                        }
                        visited[v]=1;
                        System.out.print("  "+(v+1));
                        front++;
                }
        }
        
        
    
    //reset visited Array
    void reset(){
        for(int i=0; i<visited.length;i++)
            visited[i]=0;
    }
    
}
public class Main{
        public static void main(String[] args) {
                // filename
                String filename="graph.txt";
                Scanner sc=new Scanner(System.in);
                int start;
                //declare object
                Operation obj;
                
                try {
                        obj=new Operation(filename);
                        
                        //  take input of  start vertex for dfs
                        System.out.print("\nEnter the starting  vertex to perform DFS: ");
                        start=sc.nextInt();
                        // call DFS
                        System.out.print("\nDFS from vertex "+start+": ");
                        obj.DFS(start-1);
                        
                        // check if graph is conected or not
                        if(obj.count==0)
                                System.out.print("\n\nGraph is connected.");
                        else
                                System.out.print("\n\nGraph is not connected.");
                        
                        // reset visited array
                        obj.reset();
                        
                        //  take input of  start vertex for bfs
                        System.out.print("\n\nEnter the starting  vertex to perform BFS: ");
                        start=sc.nextInt();
                        // call BFS
                        System.out.print("\nBFS from vertex "+start+": ");
                        obj.BFS(start-1);
                        System.out.print("\n");
                        
                }catch (Exception e){
                        e.printStackTrace();
                }
        }
}

___________________________________________________________________



5
1 2
1 4
2 3
3 5
4 5

___________________________________________________________________

Adjacency matrix of the graph:
0 1 0 1 0
1 0 1 0 0
0 1 0 0 1
1 0 0 0 1
0 0 1 1 0

Enter the starting  vertex to perform DFS: 1

DFS from vertex 1: 1  2  3  5  4

Graph is connected.

Enter the starting  vertex to perform BFS: 1

BFS from vertex 1:   1  2  4  3  5

___________________________________________________________________


Note: If you have queries or confusion regarding this question, please leave a comment. I would be happy to help you.


Related Solutions

Write a program in java that detects if there is a cycle in an undirected graph...
Write a program in java that detects if there is a cycle in an undirected graph using DFS Two lines of input: 1. Two integers V for the number of vertices and E for the number of edges respectively. 2. List of integers that shows how the graph is connected. Ex input: 4 4 01020323 Output: Graph contains cycle Ex input: 5 4 01020314 Output: Graph doesn't contains cycle
Given an undirected graph G = (V,E), consisting of n vertices and m edges, with each...
Given an undirected graph G = (V,E), consisting of n vertices and m edges, with each edge labeled from the set {0,1}. Describe and analyze the worst-case time complexity of an efficient algorithm to find any cycle consisting of edges whose labels alternate 0,1.
Consider an undirected graph G that has n distinct vertices. Assume n≥3. How many distinct edges...
Consider an undirected graph G that has n distinct vertices. Assume n≥3. How many distinct edges will there be in any circuit for G that contains all the vertices in G? What is the maximum degree that any vertex in G can have? What is the maximum number of distinct edges G can have? What is the maximum number of distinct edges that G can have if G is disconnected?
5. Suppose we are given both an undirected graph G with weighted edges and a minimum...
5. Suppose we are given both an undirected graph G with weighted edges and a minimum spanning tree T of G . (a) Describe an algorithm to update the minimum spanning tree when the weight of a single edge e is decreased. (b) Describe an algorithm to update the minimum spanning tree when the weight of a single edge e is increased. In both cases, the input to your algorithm is the edge e and its new weight; your algorithms...
Prove a connected simple graph G with 16 vertices and 117 edges is not Eulerian.
Prove a connected simple graph G with 16 vertices and 117 edges is not Eulerian.
Is it possible for a planar graph to have 6 vertices, 10 edges and 5 faces?...
Is it possible for a planar graph to have 6 vertices, 10 edges and 5 faces? Explain.
Let G be a simple undirected graph with n vertices where n is an even number....
Let G be a simple undirected graph with n vertices where n is an even number. Prove that G contains a triangle if it has at least (n^2 / 4) + 1 edges using mathematical induction.
Consider a grid with vertices from (0,0) to (20,20), in which edges can only be traversed...
Consider a grid with vertices from (0,0) to (20,20), in which edges can only be traversed up or right. Think of a street grid with intersections labelled by pairs of integers, and all one-way streets. How many paths, going only up and right, are there in the grid which do not pass through either forbidden intersection, if: (1) There are forbidden nodes at grid points (12,7) and (7,12)? (2) There are forbidden nodes at grid points (6,6) and (13,13)?
Draw a connected, simple graph with 6 vertices and 12 edges. Verify the Handshaking Lemma for...
Draw a connected, simple graph with 6 vertices and 12 edges. Verify the Handshaking Lemma for your graph.
Write a program in C or in Java, that takes an integer value N from the...
Write a program in C or in Java, that takes an integer value N from the command line, generates N random points in the unit square, and computes the distance separating the closest pair of points. A unit square is a square with sides of length 1, at points (0, 0), (0, 1), (1, 0), and (1, 1). If you wish to avoid the command-line processing, you can just assume you will generate a fixed number of points, say between...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT