Question

Using Java Code. Thankyou. The file has 1 edge per line in the format (origin,destination) - Ass...

Using Java Code. Thankyou.


The file has 1 edge per line in the format (origin,destination)

- Assume the graph is not directional

- (2,5) means there is a path from 2 to 5 and from 5-2


For the Lab write the following code.

1) Write a function to find all adjacent vertices to a node N ( find_adjacent(n))

2) Write a function that will return true or false that an edge exists ( edge_exists(origin,destination))

3) Print out all Vertices using BFS



Bonus +5

Print out all Vertices using DFS

Bonus +5

Write a function to print out the shortest path between two vertices (shortest_path(origin,destination))

Bonus +5

Find all Cliques in the graph and print them out

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer 1

import java.util.LinkedList;
  
public class GFG
{
// A user define class to represent a graph.
// A graph is an array of adjacency lists.
// Size of array will be V (number of vertices
// in graph)
static class Graph
{
int V;
LinkedList<Integer> find_adjacent[];
  
// constructor
Graph(int V)
{
this.V = V;
  
// define the size of array as
// number of vertices
find_adjacent = new LinkedList[V];
  
// Create a new list for each vertex
// such that adjacent nodes can be stored
for(int n = 0; n < V ;n++){
find_adjacent[n] = new LinkedList<>();
}
}
}
  
// Adds an edge to an undirected graph
static void addEdge(Graph graph, int src, int dest)
{
// Add an edge from src to dest.
graph.find_adjacent[src].add(dest);
  
// Since graph is undirected, add an edge from dest
// to src also
graph.find_adjacent[dest].add(src);
}

// A utility function to print the adjacency list
// representation of graph
static void printGraph(Graph graph)
{
for(int v = 0; v < graph.V; v++)
{
System.out.println("Adjacency list of vertex "+ v);
System.out.print("head");
for(Integer pCrawl: graph.find_adjacent[v]){
System.out.print(" -> "+pCrawl);
}
System.out.println("\n");
}
}

// Driver program to test above functions
public static void main(String args[])
{
// create the graph given in above figure
int V = 5;
Graph graph = new Graph(V);
addEdge(graph, 0, 1);
addEdge(graph, 0, 4);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);

// print the adjacency list representation of
// the above graph
printGraph(graph);
}
}

Answer 2

import java.io.*;
import java.util.*;
import java.util.LinkedList;
  
// This class represents a directed graph using adjacency list
// representation
public class Graph
{
private int V; // No. of vertices
private LinkedList<Integer> adj[]; //Adjacency List
  
//Constructor
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
  
//Function to add an edge into the graph
void addEdge(int v,int w) { adj[v].add(w); }
  
//prints BFS traversal from a given source s
Boolean edge_exists(int s, int d)
{
LinkedList<Integer>temp;
  
// Mark all the vertices as not visited(By default set
// as false)
boolean visited[] = new boolean[V];
  
// Create a queue for BFS
LinkedList<Integer> queue = new LinkedList<Integer>();
  
// Mark the current node as visited and enqueue it
visited[s]=true;
queue.add(s);
  
// 'i' will be used to get all adjacent vertices of a vertex
Iterator<Integer> i;
while (queue.size()!=0)
{
// Dequeue a vertex from queue and print it
s = queue.poll();
  
int n;
i = adj[s].listIterator();
  
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it
// visited and enqueue it
while (i.hasNext())
{
n = i.next();
  
// If this adjacent node is the destination node,
// then return true
if (n==d)
return true;
  
// Else, continue to do BFS
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
  
// If BFS is complete without visited d
return false;
}
  
// Driver method
public static void main(String args[])
{
// Create a graph given in the above diagram
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
  
int u = 1;
int v = 3;
if (g.edge_exists(u, v))
System.out.println("There is a path from " + u +" to " + v);
else
System.out.println("There is no path from " + u +" to " + v);

}

Answer 3

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

public class Breadth_First_Search {
// Function to perform breadth first search
static void breadth_First_Search(int[][] origin, int source){
boolean[] visited = new boolean[origin.length];
visited[source-1] = true;
Queue<Integer> queue = new LinkedList<>();
queue.add(source);
System.out.println("The breadth first order is");
while(!queue.isEmpty()){
System.out.println(queue.peek());
int x = queue.poll();
int i;
for(i=0; i<origin.length;i++){
if(origin[x-1][i] == 1 && visited[i] == false){
queue.add(i+1);
visited[i] = true;
}
}
}
}
// Function to read user input
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int vertices;
System.out.println("Enter the number of vertices in the graph");
try{
vertices = Integer.parseInt(br.readLine());
}catch(IOException e){
System.out.println("An error occurred");
return;
}
int[][] origin = new int[vertices][vertices];
System.out.println("Enter the adjacency matrix");
int i,j;
for(i=0; i<vertices; i++){
for(j=0; j<vertices; j++){
try{
origin[i][j] = Integer.parseInt(br.readLine());
}catch (IOException e){
System.out.println("An error occurred");
}
}
}
int source;
System.out.println("Enter the source vertex");
try{
source = Integer.parseInt(br.readLine());
}catch(IOException e){
System.out.println("An error occurred");
return;
}
breadthFirstSearch(origin,source);
}
}

Add a comment
Know the answer?
Add Answer to:
Using Java Code. Thankyou. The file has 1 edge per line in the format (origin,destination) - Ass...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • LAB 1 2 5 7 6 9 3 8 . Write code to implement an adjacency matrix (2d matrix) which represents th...

    JAVA LAB 1 2 5 7 6 9 3 8 . Write code to implement an adjacency matrix (2d matrix) which represents the graph. Your code should contain a function called addEdgelint i, int j). Use this function to add the appropriate edges in your matrix. Write code to implement Depth-First-Search (DFS) and Breadth-First-Search (BFS) of your graph. Let 0 be the source Node . Traverse the graph using DFS, print the Nodes as they are visited. . Traverse the...

  • from collections import defaultdict    # This class represents a directed graph using # adjacency list...

    from collections import defaultdict    # This class represents a directed graph using # adjacency list representation class Graph:        # Constructor     def __init__(self):            # default dictionary to store graph         self.graph = defaultdict(list)        # function to add an edge to graph     def addEdge(self,u,v):         self.graph[u].append(v)        # Function to print a BFS of graph     def BFS(self, s):            # Mark all the vertices as not visited         visited = [False] * (len(self.graph))            # Create a queue for BFS         queue...

  • Below is the Graph file that needs to be modified(using Python3) : #!/usr/bin/python3 # Simple Vertex...

    Below is the Graph file that needs to be modified(using Python3) : #!/usr/bin/python3 # Simple Vertex class class Vertex: """ Lightweight vertex structure for a graph. Vertices can have the following labels: UNEXPLORED VISITED Assuming the element of a vertex is string type """ __slots__ = '_element', '_label' def __init__(self, element, label="UNEXPLORED"): """ Constructor. """ self._element = element self._label = label def element(self): """ Return element associated with this vertex. """ return self._element def getLabel(self): """ Get label assigned to...

  • /* Graph read from file, and represnted as adjacency list. To implement DFS and BFS on...

    /* Graph read from file, and represnted as adjacency list. To implement DFS and BFS on the graph */ #include <iostream> #include <sstream> #include <fstream> #include <vector> #include <utility> #include <unordered_map> #include <set> #include <queue> using namespace std; // Each vertex has an integer id. typedef vector<vector<pair<int,int>>> adjlist; // Pair: (head vertex, edge weight) adjlist makeGraph(ifstream& ifs); void printGraph(const adjlist& alist); vector<int> BFS(const adjlist& alist, int source); // Return vertices in BFS order vector<int> DFS(const adjlist& alist, int source); //...

  • You will be implementing a Breadth-First Search (BFS) and a Depth-First Search (DFS) algorithm on a...

    You will be implementing a Breadth-First Search (BFS) and a Depth-First Search (DFS) algorithm on a graph stored as an adjacency list. The AdjacencyList class inherits from the Graph class shown below. class Graph { private: vector _distances; vector _previous; public: Graph() { } virtual int vertices() const = 0; virtual int edges() const = 0; virtual int distance(int) const = 0; virtual void bfs(int) const = 0; virtual void dfs(int) const = 0; virtual void display() const = 0;...

  • I have a Graph.java which I need to complete four methods in the java file: completeGraph(),...

    I have a Graph.java which I need to complete four methods in the java file: completeGraph(), valence(int vid), DFS(int start), and findPathBFS(int start, int end). I also have a JUnit test file GraphTest.java for you to check your code. Here is Graph.java: import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; /* Generic vertex class */ class Vertex<T> { public T data; public boolean visited; public Vertex() { data = null; visited = false; } public Vertex(T _data) { data =...

  • CSC 430              GRAPH PROJECT Implement a graph class using an adjacency matrix or an adjacency list....

    CSC 430              GRAPH PROJECT Implement a graph class using an adjacency matrix or an adjacency list. The class should have a constructor, a copy constructor, a destructor and all the methods necessary to add/delete vertices, add/delete edges… Write a menu-driven program to THOROUGHLY check your class and all the functions included in your program. You can choose the data type. Allow the user to continue with operations as long as he/she wants to. Your program should check if an operation...

  • 1.What does a file index do? Why do we need a file index? 2.Modified All-Pairs Shortest...

    1.What does a file index do? Why do we need a file index? 2.Modified All-Pairs Shortest Paths Problem This is the All-Pairs Shortest Paths problem with the following modification. Let n be the number of nodes in input graph. There are additional inputs  k1, d in [1..n]. For every path that starts at, or ends at, or passes through node k1,distance d is added to the total distance of the path. Calculate shortest distances for all pairs of nodes (as in...

  • Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, ...

    Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, to implement the depth-first search algorithm using the pseudocode given. Write a driver program, which reads input file mediumG.txt as an undirected graph and runs the depth-first search algorithm to find paths to all the other vertices considering 0 as the source. This driver program should display the paths in the following manner: 0 to ‘v’: list of all the vertices traversed to...

  • How would I traverse through this graph? Provide example code, please! class Edge {    int src,...

    How would I traverse through this graph? Provide example code, please! class Edge {    int src, dest;    Edge(int src, int dest)    {        this.src = src;        this.dest = dest;    } }; // class to represent a graph object class Graph {    // A list of lists to represent adjacency list    List<List<Integer>> adj = new ArrayList<>();    // Constructor to construct graph    public Graph(List<Edge> edges)    {        // allocate memory for adjacency list        for (int i = 0; i < edges.size(); i++) {            adj.add(i,...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT