Question

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

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

Code For Above problem:

import java.util.LinkedList;
import java.util.Queue;

public class BreathFirstTraversal {

        public static void main(String[] args) {

                int[][] g = { { 0, 1, 1, 0 }, { 0, 0, 1, 1 }, { 0, 0, 0, 1 }, { 1, 0, 0, 0 } };

                breadthFirst(g, 1);

        }

        // Function to perform breadth first traversal
        static void breadthFirst(int[][] matrix, int source) {

                // boolean array to hold visited nodes
                boolean visited[] = new boolean[matrix.length];

                // Queue to hold the track of nodes
                Queue<Integer> q = new LinkedList<Integer>();
                // add source node to queue
                q.add(source);
                // make source node as visited
                visited[source] = true;

                // do until queue become empty(all nodes are visited)
                while (!q.isEmpty()) {
                        // take the next node from queue
                        source = q.poll();
                        // print that node
                        System.out.print(source + "->");

                        // for all nodes in matrix
                        for (int i = 0; i < matrix.length; i++) {
                                // if any node which is not previously visited and adjacent to current node
                                if (!(visited[i]) && matrix[source][i] == 1) {
                                        // add those nodes to queue
                                        q.add(i);
                                        // make that nodes as visited
                                        visited[i] = true;
                                }
                        }
                }

        }

}

Output Of Above Code:

1->2->3->0->

Image Of Code:

ܢܟ le import java.util.LinkedList; 2 import java.util. Queue; 3 4 public class BreathFirstTraversal { 5 60 public static void

Output Image:

1->2->3->->

Add a comment
Know the answer?
Add Answer to:
Implement a method to take an adjacency matrix as input and print the breath-first traversal results...
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...

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

  • Implement the function hasDuplicates. Input will be given as a line containing a positive integer n,...

    Implement the function hasDuplicates. Input will be given as a line containing a positive integer n, followed by n rows, each containing a string. The output should be either the word true if there are any duplicates among these strings or false if there are not. Your code should work well on long lists of strings. Use the following set-up to write the code in JAVA import java.lang.UnsupportedOperationException; import java.util.Scanner; public class Main { public static void main(String[] args) {...

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

  • Dijkstra’s Algorithm: You have to implement the Dijkstra’s algorithm and apply it on the graph provided below. You have to take the input from the user as an adjacency matrix representing the graph,...

    Dijkstra’s Algorithm: You have to implement the Dijkstra’s algorithm and apply it on the graph provided below. You have to take the input from the user as an adjacency matrix representing the graph, the source, the destination. Then you have to apply the Dijkstra’s algorithm to find the shortest path from the source and the destination, and  find the shortest route between the source and the destination. For the input you have to read it from a file. It will...

  • Filename(s): ReformatCode. java Public class: ReformatCode Package-visible class(es): none Write a program that reformats Java source...

    Filename(s): ReformatCode. java Public class: ReformatCode Package-visible class(es): none Write a program that reformats Java source code from the next-line brace style to the end-of-line brace style. The program is invoked from the command line with the input Java source code file as args [0] and the name of the file to save the formatted code in as args [1]. The original file is left untouched. The program makes no other changes the source code, including whitespace. For example, the...

  • Code using Java What is an interface? Complete the following code: interface IExample{ public void print();...

    Code using Java What is an interface? Complete the following code: interface IExample{ public void print(); } class Example1 implements IExample{ . . . } // Driver class public class Questions { public static void main(String[] args) { . . . } } To have this message when you execute it: Implementation of an interface

  • How can I change the following program and Implement a print() method for Percolation that prints...

    How can I change the following program and Implement a print() method for Percolation that prints 1 for blocked site, 0 for open sites and * for full sites? public class Visualizeheimadaemi { public static void main(String[] args) { int N = Integer.parseInt(args[0]); double p = Double.parseDouble(args[1]); int M = Integer.parseInt(args[2]); // repeatedly created N-by-N matrices and display them using standard draw for (int i = 0; i < M; i++) { boolean[][] open = Percolation.random(N, p); StdDraw.clear(); StdDraw.setPenColor(StdDraw.BLACK); Percolation.show(open,...

  • JAVA- Complete the code by following guidelines in comments. class CircularList { private Link current; private...

    JAVA- Complete the code by following guidelines in comments. class CircularList { private Link current; private Link prev; public CircularList() { // implement: set both current and prev to null } public boolean isEmpty() { // implement return true; } public void insert(int id) { // implement: insert the new node behind the current node } public Link delete() { // implement: delete the node referred by current return null; } public Link delete(int id) { // implement: delete the...

  • Write in Java Implement the parse method and test it by calling with three different strings...

    Write in Java Implement the parse method and test it by calling with three different strings and by printing the results. The Scanner method can be used to read values from strings, files, or System.in. We need to invoke the useDelimiter method to define what symbols can separate, or terminate, the digits of a Fraction. public static Fraction parse(String input) t Scanner s new Scanner(input) useDelimitercTVMitln"); int num s.nextlnt() int denom s.nextlnt); s.close): return new Fraction(num, denom) class Codechef static...

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