Question

Exercise 1 Adjacency Matrix In this part, you will implement the data model to represent a graph. Implement the following clathe second constructor expects a two dimensional array as argument and initializes the instance variable array to it. Graph i

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 single edge in the graph consisting of the starting node, end node, and weight of the edge. The Edge must have all methods in the following class diagram. Implement hashCode() and equals(..) methods which are both based on the from, to, and weight instance variables Edge Node from - Node to; - int weight; +Edge(Node from, Node to, int weight) +Node getFromO +Node getToO +int getWeight0) +int hashCode0) +boolean equals(Object o) +String toString0 Graph.java: This class has only one instance variable that stores a two-dimensional integer array. This array represents an adjacency matrix that can represent any weighted directed graph. Implement two constructors the default constructor initializes the array to represent the graph below
the second constructor expects a two dimensional array as argument and initializes the instance variable array to it. Graph intII matrix +GraphO +Graph(int[IJl] adjacencyMatrix) +boolean hasEdge(Node from, Node to) tint weight(Node from, Node to) +List-Edge> getOutgoingEdges(Node from) +List Node> getNodes) 4 0 5 6String toString0 The Graph class must have all methods in the following class diagram. A description for each method is given below Below is a description for each of the functions inside the Graph class Checks if an edge exists Hint:the value in the instance variable array at [from] [to] is not 0 public boolean hasEdge(Node from, Node to) Returns the weight of the specified edge *Hint: Return the value in the instance variable array at [from]Cto] ereturn Weight if edge exists, 0 if no edge exists public int weight (Node from, Node to) Returns a list of outgoing edges that start at the given node Hint: Loop through the row at from and create an edge for each column with *from-row, to-column, weight-[row] [column] public List getOutgoingEdges(Node from) Returns a list of all nodes in the graph Hint: Use a loop from 0 to instance array.length to create the nodes public List getNodesO
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Node.java

public class Node {
   private int number;
   //constructor
   public Node(int number)
   {
       this.number=number;
   }
   //method to return node number
   public int getNumber()
   {
       return number;
   }
   //hashcode method
   @Override
   public int hashCode() {
       final int prime = 31;
       int result = 1;
       result = prime * result + number;
       return result;
   }
   //equals method
   @Override
   public boolean equals(Object obj) {
       Node other=(Node)obj;
       if (number != other.getNumber())
           return false;
       else
           return true;
   }
   //to string method
   @Override
   public String toString() {
       return "Node [number=" + number + "]";
   }
}

Edge.java

public class Edge {
   private Node from;
   private Node to;
   int weight;
   //constructor
   public Edge(Node from, Node to, int weight) {
       super();
       this.from = from;
       this.to = to;
       this.weight = weight;
   }
   /**
   * @return the from
   */
   public Node getFrom() {
       return from;
   }
   /**
   * @return the to
   */
   public Node getTo() {
       return to;
   }
   /**
   * @return the weight
   */
   public int getWeight() {
       return weight;
   }
   //hashcode method
   @Override
   public int hashCode() {
       final int prime = 31;
       int result = 1;
       result = prime * result + ((from == null) ? 0 : from.hashCode());
       result = prime * result + ((to == null) ? 0 : to.hashCode());
       result = prime * result + weight;
       return result;
   }
   //equals method
   @Override
   public boolean equals(Object obj) {
       Edge other = (Edge) obj;
       if (from == null) {
           if (other.from != null)
               return false;
       } else if (!from.equals(other.from))
           return false;
       if (to == null) {
           if (other.to != null)
               return false;
       } else if (!to.equals(other.to))
           return false;
       if (weight != other.weight)
           return false;
       return true;
   }
   @Override
   public String toString() {
       return "Edge [from=" + from + ", to=" + to + ", weight=" + weight + "]";
   }
  

}

Graph.java

import java.util.ArrayList;
import java.util.List;

public class Graph {
   private int[][] matrix;
   //default constructor
   public Graph()
   {
       //adijency matrix based on the graph
       int i[][]={{0,5,2,0,0,0,0},{5,0,0,1,0,0,0},{2,0,0,2,0,0,8},{0,1,2,0,2,1,0},{0,0,0,2,0,0,3},{0,0,0,1,0,0,0},{0,0,8,0,3,0,0}};
       matrix=new int[7][7];
       for(int j=0;j<7;j++)
           for(int k=0;k<7;k++)
               matrix[j][k]=i[j][k];
   }
   //constructor to initialize the matrix
   public Graph(int[][] matrix) {
       super();
       this.matrix = matrix;
   }
   //method to detect the is edge is present or not
   public boolean hasEdge(Node from,Node to)
   {
       if(matrix[from.getNumber()][to.getNumber()]==0)
       {
           return false;
       }
       else
       {
           return true;
       }
   }
   //method to return the weight of the graph
   public int weight(Node from,Node to)
   {
       return matrix[from.getNumber()][to.getNumber()];
   }
   //method to return this list of outgoing edges
   public List<Edge> getOutgoingEdges(Node from)
   {
       List<Edge> li=new ArrayList<Edge>();
       int j=from.getNumber();
       for(int i=0;i<matrix[j].length;i++)
       {
           if(matrix[j][i]!=0)
           {
               li.add(new Edge(new Node(j),new Node(i),matrix[i][j]));
           }
       }
       return li;
      
   }
   //method to return the list of nodes
   public List<Node> getNodes()
   {
       List<Node> li=new ArrayList<Node>();
       for(int i=0;i<matrix.length;i++)
       {
           li.add(new Node(i));
       }
       return li;
      
   }

}

//sample driver class

import java.util.List;

public class Demo {
   public static void main(String args[])
   {
       Graph ob=new Graph();
       List<Node> li=ob.getNodes();

      //to print list for nodes
       System.out.println(li);
       List<Edge>oe=ob.getOutgoingEdges(new Node(4));

   //to print the edges
       System.out.println(oe);
   }

}

output:

<terminated> Demo [Java Application]/usr/lib/jvm/java-11-oracle/bin/java (30-May-2019, 11:14:32 am) [Node [number-0], Node [n

if you have any doubt are any changes in the program please do comment..

Add a comment
Know the answer?
Add Answer to:
Exercise 1 Adjacency Matrix In this part, you will implement the data model to represent a graph. Implement the followi...
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
  • 1. a. Using C++, represent the following graph using adjacency matrix, and implement DFS by using...

    1. a. Using C++, represent the following graph using adjacency matrix, and implement DFS by using stack (define it using class) to traverse the graph. b. Similarly, implement BFS (define queue using class) to traverse the graph c.When node 6 is printed, what numbers are in the stack (for DFS) and queue (for BFS) respectively? Draw pictures to show them. 1. a. Using C++, represent the following graph using adjacency matrix, and implement DFS by using stack (define it using...

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

  • Implement a method to take an adjacency matrix as input and print the breath-first traversal results...

    Implement a method to take an adjacency matrix as input and print the breath-first traversal results of the graph starting from a node. CODE: ______________________________________________________________________________________________ public class A5_Q1{ public static void breathFirst(int [] [] aMatrix, int source) { // complete the code } public static void main (String[] args) { int [] [] g = {{0,1,1,0}{0,0,1,1}{0,0,0,1}{1,0,0,0}}; breathFirst(g, 1); } } _____________________________________________________________________________________________ Example of input and output: >java A5_Q1 1->2->3 >0

  • Code in JAVA You are asked to implement “Connect 4” which is a two player game....

    Code in JAVA You are asked to implement “Connect 4” which is a two player game. The game will be demonstrated in class. The game is played on a 6x7 grid, and is similar to tic-tac-toe, except that instead of getting three in a row, you must get four in a row. To take your turn, you choose a column, and slide a checker of your color into the column that you choose. The checker drops into the slot, falling...

  • 1. a. Using C++, represent the following graph using adjacency matrix, and implement depth first searching...

    1. a. Using C++, represent the following graph using adjacency matrix, and implement depth first searching (DFS) by stack (define it with class) to traverse the graph. 6 7 2 4 b. If starting with node 2, when node 7 is printed, what numbers are in the stack (for DFS)? Please draw the stack step by step to show how the numbers are pushed into and popped out of it. 2. a. Given a set of integer numbers as int...

  • In the first exercise, you will override the add method in a subclass in order to...

    In the first exercise, you will override the add method in a subclass in order to improve its performance. In the second exercise, you will implement an Iterator for your new linked list class. Exercise 1 The add method of the linked list class discussed during lecture performs in O(N) time. What can be done to improve its performance to O(1)? What are the boundary cases? Define a new class that inherits from the CS20bLinkedList class introduced during the lecture....

  • 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,...

  • 1. Assume you have a Car class that declares two private instance variables, make and model....

    1. Assume you have a Car class that declares two private instance variables, make and model. Write Java code that implements a two-parameter constructor that instantiates a Car object and initializes both of its instance variables. 2. Logically, the make and model attributes of each Car object should not change in the life of that object. a. Write Java code that declares constant make and model attributes that cannot be changed after they are initialized by a constructor. Configure your...

  • Introduction In this lab, you are supposed to implement a graph class with the data structure...

    Introduction In this lab, you are supposed to implement a graph class with the data structure implemented before like linked list and queue. graph The class graph contains three member variables: linkedList *adjacentVertices; //an array of linked list. For a vertice i, adjacentVertices[i] stores the linked list that contains all other vertices connected to vertice i. int numVertices; //The number of vertices in the graph. int maxNumVertices; //The maximum number of vertices the graph can hold. Following public methods are...

  • Please help me with this code. Thank you Implement the following Java class: Vehicle Class should...

    Please help me with this code. Thank you Implement the following Java class: Vehicle Class should contain next instance variables: Integer numberOfWheels; Double engineCapacity; Boolean isElectric, String manufacturer; Array of integers productionYears; Supply your class with: Default constructor (which sets all variables to their respective default values) Constructor which accepts all the variables All the appropriate getters and setters (you may skip comments for this methods. Also, make sure that for engineCapacity setter method you check first if the vehicle...

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