Question

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, new ArrayList<>());
       }

       // add edges to the undirected graph
       for (Edge current : edges)
       {
           // allocate new node in adjacency List from src to dest
           adj.get(current.src).add(current.dest);

           // Uncomment line 39 for undirected graph

           // allocate new node in adjacency List from dest to src
           // adj.get(current.dest).add(current.src);
       }
   }
}

class Main
{
   // print adjacency list representation of graph
   private static void printGraph(Graph graph)
   {
       int src = 0;
       int n = graph.adj.size();

       while (src < n)
       {
           // print current vertex and all its neighboring vertices
           for (int dest : graph.adj.get(src)) {
               System.out.print("(" + src + " --> " + dest + ")\t");
           }

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

   // Directed Graph Implementation in Java
   public static void main (String[] args)
   {
       // Input: List of edges in a directed graph (as per above diagram)
       List<Edge> edges = Arrays.asList(new Edge(0, 1), new Edge(1, 2),
                                   new Edge(2, 0), new Edge(2, 1),new Edge(3, 2),
                                   new Edge(4, 5), new Edge(5, 4));

       // construct graph from given list of edges
       Graph graph = new Graph(edges);

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

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

In the given code, the graph is saved as an adjecency list. There are in total two ways of representing a graph in an algorithm. An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a vertex in the graph.

Think of the data structure as a list of list of integers. See this line: List<List<Integer>> adj = new ArrayList<>();

This means we have a list (linked list) of many sources and each of those sources have various destinations in the graph. Have a look at this adjecency list (a vertical stack of source nodes and a list of other nodes which are connected to this particular node):

2 3 5 2 5 0 3 4 2 5 2 어 4 2 3 2 3/ 2 4 4 0 0 --O-27 4 5 0 (b) (a) (c)

Now, you have (b) which is an adjecency list. (c) denotes an adjecency matrix.

For traversing through the graph you can use the following process:

Let's say you are trying to reach node 3 from node 2 from node 1. In a gist 1 -> 2 -> 3

step 1: select a starting node (may be 1)

step 2: in the List, search for the first node (node 1) and then search the list associated with (1) if node (2) exists there. The nodes associated with (1) are 2 and 5 so you are sure that 2 exists.

step 3: since 2 was there in list of node 1, you can be sure that you can reach 2, now try searching node 3 in the second node's list. in the List, search for the second node (node 2) and then search the list associated with (2) if node (3) exists there.

since 3 exists, we have traversed from 1 to 3

The code will look as follows:

private static void goFrom1To3Graph(Graph graph)
   {
       int src = 1;
       int n = graph.adj.size();
       for (int dest : graph.adj.get(src)) {
           System.out.print("(" + src + " --> " + dest + ")\t");

if (dest == 2) {

for(int dest2 : graph.adj.get((2)) {

  System.out.print("(" + 2 + " --> " + dest + ")\t");

if (dest2 == 3)

System.out.println("reached 3 through 2 through 1");

}

}
       }
   }

Add a comment
Know the answer?
Add Answer to:
How would I traverse through this graph? Provide example code, please! class Edge {    int src,...
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
  • How to solve my code for my Deliv C program?

    ProgramIntro.pngProgramIntro2.pngProgramIntro1.pngProgram1.pngProgram2.pngGraph Class:import java.util.ArrayList;//Graph is a class whose objects represent graphs. public class Graph {    ArrayList<Node> nodeList;    ArrayList<Edge> edgeList;       public Graph() {        nodeList = new ArrayList<Node>();        edgeList = new ArrayList<Edge>();       }       public ArrayList<Node> getNodeList() {        return nodeList;   }   public ArrayList<Edge> getEdgeList() {        return edgeList;   }   public void addNode(Node n) {        nodeList.add(n);   }   public void addEdge(Edge e) {        edgeList.add(e);   }   public String...

  • How can I solved my Java Program for DelivC

    //Graph Class: import java.util.ArrayList; //Graph is a class whose objects represent graphs.  public class Graph {     ArrayList<Node> nodeList;     ArrayList<Edge> edgeList;         public Graph() {         nodeList = new ArrayList<Node>();         edgeList = new ArrayList<Edge>();         }         public ArrayList<Node> getNodeList() {         return nodeList;    }    public ArrayList<Edge> getEdgeList() {         return edgeList;    }    public void addNode(Node n) {         nodeList.add(n);    }    public void addEdge(Edge e) {         edgeList.add(e);    }    public String toString() {         String s = "Graph g.\n";         if (nodeList.size() > 0) {             for (Node n : nodeList) {         // Print node info         String t = "\nNode " + n.getName() + ", abbrev " + n.getAbbrev() + ", value " + n.getVal() + "\n";         s = s.concat(t);         }         s = s.concat("\n");             }         return s;     }  } // Node Class: import java.util.ArrayList;  // Node is a class whose objects represent nodes (a.k.a., vertices) in the graph.  public class Node {    String name;     String val; // The value of the Node     String abbrev; // The abbreviation for the Node     ArrayList<Edge> outgoingEdges;     ArrayList<Edge> incomingEdges;             String color; //Create the color of the TYPE Node List     int start; //Create the Starting Time     int end; //Create the Ending Time             public Node( String theAbbrev ) {         setAbbrev( theAbbrev );         val = null;         name = null;         outgoingEdges = new ArrayList<Edge>();         incomingEdges = new ArrayList<Edge>();     }         public String getAbbrev() {         return abbrev;     }         public String getName() {         return name;     }         public String getVal() {         return val;     }         public ArrayList<Edge> getOutgoingEdges() {         return outgoingEdges;     }         public ArrayList<Edge> getIncomingEdges() {         return incomingEdges;...

  • Consider the java Graph class below which represents an undirected graph in an adjacency list. How...

    Consider the java Graph class below which represents an undirected graph in an adjacency list. How would you add a method to delete an edge from the graph? // Exercise 4.1.3 (Solution published at http://algs4.cs.princeton.edu/) package algs41; import stdlib.*; import algs13.Bag; /** * The <code>Graph</code> class represents an undirected graph of vertices * named 0 through V-1. * It supports the following operations: add an edge to the graph, * iterate over all of the neighbors adjacent to a vertex....

  • Hi there. I tried to submit this before, but the copy/paste didn't copy my vectors correctly....

    Hi there. I tried to submit this before, but the copy/paste didn't copy my vectors correctly. Hello there. I am trying to implement the djikstras shortest path algorithm into my code in C++ with a vector of vectors. However, when I test I get an error "Exception thrown at 0x75FFC762 in graphMain.exe: Microsoft C++ exception: std::out_of_range at memory location 0x009CF26C" for line 115 in graph.cpp. Could you help me debug? I am so close! ----------------------------FILE NAME: pch.h--------------------------------------- // pch.cpp: source...

  • public class F2{ public static int foo(ArrayList<Integer> a) { int sum = 0; for(int i =...

    public class F2{ public static int foo(ArrayList<Integer> a) { int sum = 0; for(int i = 0; i <a.size(); i++){ if(i % 3 == 1) sum += a.get(i); else if(i % 3 == 2) sum -= a.get(i); else sum++; } return sum; } } What do the following method calls return? 1. foo(new ArrayList<>(Arrays.asList(1,2,3,4))) 2. foo(new ArrayList<>()) 3. foo(new ArrayList<>(Arrays.asList(1,2,-3,4325,-2))) 4. foo(new ArrayList<>(Arrays.asList(0,0,0)))

  • Exercise 1 Adjacency Matrix In this part, you will implement the data model to represent a graph. Implement the followi...

    Exercise 1 Adjacency Matrix In this part, you will implement the data model to represent a graph. Implement the following classes Node.java: This class represents a vertex in the graph. It has only a single instance variable of type int which is set in the constructor. Implement hashCode() and equals(..) methods which are both based on the number instance variable Node - int number +Node(int number); +int getNumberO; +int hashCode() +boolean equals(Object o) +String toString0) Edge.java: This class represents a...

  • Preliminaries Download the template class and the driver file. Objective Learn how to traverse a binary...

    Preliminaries Download the template class and the driver file. Objective Learn how to traverse a binary search tree in order. Description For the template class BinarySearchTree, fill in the following methods: insert - Inserts values greater than the parent to the right, and values lesser than the parent to the left.parameters elem - The new element to be inserted into the tree. printInOrder - Prints the values stored in the tree in ascending order. Hint: Use a recursive method to...

  • Can someone provide codes in C for the following questions: Write C programs grah.h and graph.c...

    Can someone provide codes in C for the following questions: Write C programs grah.h and graph.c to implement adjacent list graph representation and operation functions. Test with q1.c. graph.h #ifndef GRAPH_H #define GRAPH_H #include <stdio.h> #include <stdlib.h> #define INFINITY 99999 typedef struct adjnode { int vertex; int weight; struct adjnode *next; } ADJNODE; typedef struct graph { int order; //number of nodes int size; //number of edges ADJNODE **adjlist; //pointer to an array of pointers of neighbors } GRAPH; /*...

  • Hello, i am working on java program which implements Graph as an adjacency list structure. code...

    Hello, i am working on java program which implements Graph as an adjacency list structure. code is the implementation of RailNetwork. i need help to change the code so it could hold String instead of integers. so, for example, Station "Station name" is connected to "Station name" and also i need to add class edge which basically will be a direction for those give stations. so the output will be like "Station name" is connected to "Station name" with "this...

  • #include <iostream> #include <queue> using namespace std; class Graph { public: Graph(int n); ~Graph(); void addEdge(int...

    #include <iostream> #include <queue> using namespace std; class Graph { public: Graph(int n); ~Graph(); void addEdge(int src, int tar); void BFTraversal(); void DFTraversal(); void printVertices(); void printEdges(); private: int vertexCount; int edgeCount; bool** adjMat; void BFS(int n, bool marked[]); void DFS(int n, bool marked[]); }; Graph::Graph(int n=0) { vertexCount = n; edgeCount = 0; if(n == 0) adjMat = 0; else { adjMat = new bool* [n]; for(int i=0; i < n; i++) adjMat[i] = new bool [n]; for(int i=0;...

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