Question

USING JAVA: Create a class: AdjListGraph.java, and just submit AdjListGraph.java. where -Step 1(1 credit): Please implement...

USING JAVA:

Create a class: AdjListGraph.java, and just submit AdjListGraph.java. where

-Step 1(1 credit):

Please implement a graph by adjacency list.

-Step 2(1 credit):

Write a method: void dfs(){\\ TO-DO}; which can traverse a graph by DFS(stack based or recursive)

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

(i) Implementing Adjacency list graph.

class AdjListNode //create a class for adj list node

{

    int dest;

    AdjListNode next;

    public AdjListNode(int dest)

{

        this.dest = dest;

        this.next = null;

    }

}

class AdjListGraph

{

    AdjListNode head;

}

public class graph

{

    int V;

    AdjListNode newNode;

    AdjList array[];

    public graph(int V)

{

    this.V = V;

    this.array = new AdjList[V];

    int i;

    for(i=0;i<V;++i)

{

        this.array[i] = new AdjList();

    }

}

   

void addEdge(graph g, int src, int dest)

{

        newNode = new AdjListNode(dest);

        newNode.next = g.array[src].head;

        g.array[src].head = newNode;

        newNode = new AdjListNode(src);

        newNode.next = g.array[dest].head;

        g.array[dest].head = newNode;

    }

    void printGraph(graph g)

{

        int v;

        for(v=0;v < g.V;++v)

{

            AdjListNode pCrawl = g.array[v].head;

            System.out.println();

            System.out.println("Adjacency list of vertex "+v);

            System.out.print("head");

            while(pCrawl != null)

{

                System.out.print(pCrawl.dest);

                pCrawl = pCrawl.next;

            }

            System.out.println();

        }

    }

    public static void main(String[] args)

{

        int V = 5;

       graph g = new graph(V);

        g.addEdge(g,0,1);

        g.addEdge(g,0,4);

        g.addEdge(g,1,2);

        g.addEdge(g,1,3);

        g.addEdge(g,1,4);

        g.addEdge(g,2,3);

        g.addEdge(g,3,4);

        g.printGraph(g);

    }

}

(ii) DFS traversal of a graph (stack based)

class StackX

{

            private final int SIZE = 20;

            private int[] st;

            private int top;

            // constructor

            public StackX()

            {

                        st = new int[SIZE];     //make array

                        top = -1;

            }

            //push item into stack

            public void push(int j)

            { st[++top] = j; }

            //pop item from stack

            public int pop()

            { return st[top--]; }

            //peek at top of stack

            public int peek()

            { return st[top]; }

            //true if nothing on stack

            public boolean isEmpty()

            {

return top == -1; }

} // end class StackX

//

class DFSLink

{

            public int vertex;

            public DFSLink next;            

}

class DFSList

{

            public DFSLink head;

            public DFSList()

            {

                        head = new DFSLink();

                        //head is given a dummy value so searches

                        //don't necessarily include vertex A (0)

                        head.vertex = -1;

            }

           

            public void insert(int v)

            {

                        DFSLink cur = head;

                        while(cur.next != null)

                                    cur = cur.next;

                        cur.next = new DFSLink();

                        cur.next.vertex = v;

            }

           

            public DFSLink deleteFromEnd()

            {

                        if(head == null) return null;

                        DFSLink cur = head;

                        while(cur.next.next != null)

                                    cur = cur.next;

                        DFSLink temp = cur.next;

                        cur.next = null;

                        return temp;

            }

           

            public boolean contains(int j)

            {

                        DFSLink cur = head;

                        while(cur != null)

                        {

                                    if(cur.vertex == j) return true;

                                    cur = cur.next;

                        }

                        return false;

            }

}

class DFSGraph

{

            private final int MAX_VERTS = 20;

            private Vertex[] vertexList;   //list of vertices

            private DFSList[] adjMat;      //adjacency matrix

            private int nVerts;                   //current number of vertices

            private StackX theStack;

            //Constructor

            public DFSGraph()

            {

                        vertexList = new Vertex[MAX_VERTS];     //adjacency matrix

                        adjMat = new DFSList[MAX_VERTS];

                        nVerts = 0;

                         // set adjacency matrix to zero

                        for(int j = 0; j < MAX_VERTS; j++)

                                    adjMat[j] = new DFSList();

                        theStack = new StackX();

            }

            public void addVertex(char lab)

            {

                        vertexList[nVerts++] = new Vertex(lab);

            }

           

            //creates an edge from one vertex to another.

            //DIRECTED GRAPH, not undirected

            public void addEdge(int start, int end)

            {

                        adjMat[start].insert(end);

            }

           

            public void displayVertex(int j)

            {

                        System.out.print(vertexList[j].label);

            }

           

            //depth first search

            public void dfs(int start)

            {

                        vertexList[start].wasVisited = true; //begin

                        displayVertex(start);               //display it

                        theStack.push(start);               //push it

                       

                        while(!theStack.isEmpty())    //until stack is empty

                        {

                                // get an unvisited vertex adjacent to stack top

                                    int v = getAdjUnvisitedVertex(theStack.peek());

                                    if(v == -1)                   //if no such vertex

                                                theStack.pop();

                                    else                  //if it exists

                                    {

                                                vertexList[v].wasVisited = true;

                                                displayVertex(v);        //display it

                                                theStack.push(v);        //push it

                                    }

                        }

                        System.out.println();

                        for(int j = 0; j < nVerts; j++)

                                    vertexList[j].wasVisited = false;

            }

            //unvisited vertex

            public int getAdjUnvisitedVertex(int v)

            {

                        for(int j = 0; j < nVerts; j++)

                                    if(adjMat[v].contains(j) && vertexList[j].wasVisited == false)

                                                return j;

                        return -1;

            }

} // end class DFSGraph

class DFSApp

{

            public static void main(String[] args)

            {

                        DFSGraph theGraph = new DFSGraph();

                        theGraph.addVertex('A');

                        theGraph.addVertex('B');

                        theGraph.addVertex('C');

                        theGraph.addVertex('D');

                        theGraph.addVertex('E');

                       

                        theGraph.addEdge(0, 1);

                        theGraph.addEdge(2, 1);

                        theGraph.addEdge(2, 3);

                        theGraph.addEdge(3, 1);

                        theGraph.addEdge(4, 2);

                       

                        System.out.println("visits:");

                        theGraph.dfs ();

                        System.out.println();

            } //end main()

}

Add a comment
Know the answer?
Add Answer to:
USING JAVA: Create a class: AdjListGraph.java, and just submit AdjListGraph.java. where -Step 1(1 credit): Please implement...
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...

  • refer to the question using c++. if you could not do the bonus part no problem you don't have too , but if you can so please do it and let me know Create an unweighted undirected Graph Class usin...

    refer to the question using c++. if you could not do the bonus part no problem you don't have too , but if you can so please do it and let me know Create an unweighted undirected Graph Class using an Adjacency Matrix with the following functions 1. Graph(int numofV) 3. int noOfOutgoingEdges(int vertex); 4. int noOflncomingEdges (int vertex) 5. void print) You may use vectors/2D dynamic arrays to implement the matrix. Bonus (20) 6. void DFS(); Depth First Search...

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

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

  • Help with Java Program Please Create a simple graph class. The graph class should have the...

    Help with Java Program Please Create a simple graph class. The graph class should have the following items: an adjacency list or matrix to hold the graph data variables to hold the current size and max size of the graph default constructor create empty adjacency list/matrix max size = 10 overloaded constructor create empty adjacency list/matrix max size = int parameter isEmpty check if current size is zero createGraph read a formatted file and fill adjacency list/matrix The first line...

  • JAVA coding The Sorted List ADT Implement the SortedList class. The SortedList class extends the ...

    JAVA coding The Sorted List ADT Implement the SortedList class. The SortedList class extends the AbstractList class. Both can be seen here. Your assignment is to implement (recursively) all of the abstract methods of the AbstractList class. They are: insert (recursive) iterator remove (recursive) retrieve search (recursive) You must also implement an Iterator inner class for the SortedList class. You must submit a modified SortedList.java file with your source code. Do not submit and do not modify the List.java or...

  • Using Java You are given a Node class and a List class: public class Node {...

    Using Java You are given a Node class and a List class: public class Node {    int   data;     Node next; } public class List {     Node first; } You are also given a Stack class. The following functions are available for use: public class Stack { public boolean isEmpty(){}; public void push(int n){}; public int pop(){};} Write a Java method snglyRevToStck that pushes the data found in a linked list t in reverse order into the stack...

  • Implement an array-based Linked List in Java. Use double as the item. You need to create...

    Implement an array-based Linked List in Java. Use double as the item. You need to create a driver includes several items and inserts them in order in a list. Identify the necessary methods in a List Linked implementation. Look at previous Data Structures (stack or queue) and be sure to include all necessary methods. DO NOT USE your language's Library List. You will receive zero points. Write a LinkedList class Write a driver (tester) call LinkListedDriver to show you have...

  • ANSWER IN JAVA ASAP 1.Implement a stack on the singly linked list with the operations of...

    ANSWER IN JAVA ASAP 1.Implement a stack on the singly linked list with the operations of Lab Assignment 1. Hint: Using the same Stack class you implemented, change the array to an object of the singly linked list class. The functionality of push and pop is now based on the methods of the linked list class.

  • can you solve it in java please Create the following: 1. Class Invoice ( the node...

    can you solve it in java please Create the following: 1. Class Invoice ( the node ) that includes three instance variables:     int No; // the Invoice No             String CustName; // the Customer name             int Amount; // the Invoice Amount Invoice next; // points to the next Invoice Default and overloaded constructors 2. Class Shop that includes three instance variables: Invoice head; Invoice Tail; Your class should have the following: • A method that initializes the instance variables....

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