Question

in c++ and in one function please Print All possible Paths Implement the following member function:...

in c++ and in one function please

Print All possible Paths

Implement the following member function: PrintPaths(int u, int v). This function prints all possible paths from vertex u to vertex v. Assume that the graph doesn't contain cycles.

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

Code For Above problem:


// C++ program to print all paths from a source to destination. 
#include<iostream> 
#include <list> 
using namespace std; 
  
// A directed graph using adjacency list representation 
class Graph 
{ 
    int V; // No. of vertices in graph 
    list<int> *adj; // Pointer to an array containing adjacency lists 
  
    // A recursive function used by printAllPaths() 
    void printAllPathsUtil(int , int , bool [], int [], int &); 
  
public: 
    Graph(int V); // Constructor 
    void addEdge(int u, int v); 
    void printAllPaths(int s, int d); 
}; 
  
Graph::Graph(int V) 
{ 
    this->V = V; 
    adj = new list<int>[V]; 
} 
  
void Graph::addEdge(int u, int v) 
{ 
    adj[u].push_back(v); // Add v to u’s list. 
} 
  
// Prints all paths from 's' to 'd' 
void Graph::printAllPaths(int s, int d) 
{ 
    // Mark all the vertices as not visited 
    bool *visited = new bool[V]; 
  
    // Create an array to store paths 
    int *path = new int[V]; 
    int path_index = 0; // Initialize path[] as empty 
  
    // Initialize all vertices as not visited 
    for (int i = 0; i < V; i++) 
        visited[i] = false; 
  
    // Call the recursive helper function to print all paths 
    printAllPathsUtil(s, d, visited, path, path_index); 
} 
  
// A recursive function to print all paths from 'u' to 'd'. 
// visited[] keeps track of vertices in current path. 
// path[] stores actual vertices and path_index is current 
// index in path[] 
void Graph::printAllPathsUtil(int u, int d, bool visited[], 
                            int path[], int &path_index) 
{ 
    // Mark the current node and store it in path[] 
    visited[u] = true; 
    path[path_index] = u; 
    path_index++; 
  
    // If current vertex is same as destination, then print 
    // current path[] 
    if (u == d) 
    { 
        for (int i = 0; i<path_index; i++) 
            cout << path[i] << " "; 
        cout << endl; 
          
    } 
    else // If current vertex is not destination 
    { 
        // Recur for all the vertices adjacent to current vertex 
        list<int>::iterator i; 
        for (i = adj[u].begin(); i != adj[u].end(); ++i) 
            if (!visited[*i]) 
                printAllPathsUtil(*i, d, visited, path, path_index); 
    } 
  
    // Remove current vertex from path[] and mark it as unvisited 
    path_index--; 
    visited[u] = false; 
} 
  
// Driver program 
int main() 
{ 
    // Create a graph given in the above diagram 
    Graph g(4); 
    g.addEdge(0, 1); 
    g.addEdge(0, 2); 
    g.addEdge(0, 3); 
    g.addEdge(2, 0); 
    g.addEdge(2, 1); 
    g.addEdge(1, 3); 
  
    int s = 2, d = 3; 
    cout << "Following are all different paths from " << s 
        << " to " << d << endl; 
    g.printAllPaths(s, d); 
  
    return 0; 
} 

Output Of Above Code:

Following are all different paths from 2 to 3
2 0 1 3 
2 0 3 
2 1 3 

Images Of Code:

10 12 20 26 117 C++ program to print all paths from a source to destination. 2 #include<iostream> 3 #include <list> 4 using n

56 { 57 58 59 60 61 62 63 64 66 52 // path[] stores actual vertices and path_index is current 53 // index in path[] 54 void G

Image Of Output:

apiiit-rkv@apiiitrkv-TravelMate-P243-M:-/Desktop$ 9++ AllPaths.cpp apiiit-rkv@apiiitrkv-TravelMate-P243-M :-/Desktop$ ./a.out

Add a comment
Know the answer?
Add Answer to:
in c++ and in one function please Print All possible Paths Implement the following member function:...
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
  • DO ALL OR DON'T ANSWER. Print all possible solutions to N Queens problem Print all Possible...

    DO ALL OR DON'T ANSWER. Print all possible solutions to N Queens problem Print all Possible Knight's Tours in a chessboard Magnet Puzzle Find Shortest Path in Maze Find Longest Possible Route in a Matrix Find path from source to destination in a matrix that satisfies given constraints Find total number of unique paths in a maze from source to destination Print All Hamiltonian Path present in a graph Print all k-colorable configurations of the graph (Vertex coloring of graph)...

  • in c++ The Bellman-Ford Algorithm In this assignment, you are asked to implement the Bellman-Ford Algorithm...

    in c++ The Bellman-Ford Algorithm In this assignment, you are asked to implement the Bellman-Ford Algorithm which solves the single-source shortest-paths problem. Specifically, you are given as input a directed graph G = (V. E) with weight w(u, v) on each edge (u, v) E E along with a source vertex s EV. Edges may have negative weights. Input The input has the following format. There are two integers on the first line. The first integer represents the number of...

  • 28. Implement an overloaded member function of the IntVector class named assign. This version of assign passes in an ar...

    28. Implement an overloaded member function of the IntVector class named assign. This version of assign passes in an array of integers, along with 2 unsigned index values. This function may assume the indices are valid (i.e., does no bounds error checking on the array passed in). For example, if you have an array of integers named iarr with a size of 10, you can call assign on an IntVector named v like this: int iarr[] 1, 2, 3, 4,...

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

  • Please give an answer which works to print the answer given below. Please use the necessary...

    Please give an answer which works to print the answer given below. Please use the necessary header .h and .cpp files. Please give the right solution. "ITS MY HUMBLE REQUEST TO GIVE THE RIGHT SOLUTION" Question 2 – Creating and working with other Containers A Set is a data structure which contains information on whether a value belongs to that set or not. In this question, you have to implement an integer Set which is able to tell whether an...

  • Design and implement a C++ class called Date that has the following private member variables month...

    Design and implement a C++ class called Date that has the following private member variables month (int) day (nt) . year (int Add the following public member functions to the class. Default Constructor with all default parameters: The constructors should use the values of the month, day, and year arguments passed by the client program to set the month, day, and year member variables. The constructor should check if the values of the parameters are valid (that is day is...

  • Please write the complete code in C. Write a C function that prints the minimum spanning...

    Please write the complete code in C. Write a C function that prints the minimum spanning tree of a graph. At the end, print the weight of the spanning tree. A suggested report format is shown in the following example. Source Vertex To Vertex Weight A B 2 A C 4 B D 3 D E 1 Total weight of spanning tree: 10 Your main program will read a graph from DataIn file to an adjacency table before calling the...

  • In C++ and comment so I UNDERSTAND Implement a class named DynamicArray that has the following...

    In C++ and comment so I UNDERSTAND Implement a class named DynamicArray that has the following members: A pointer to hold a dynamically allocated array, of type int. A member variable to hold the size of the array. A default constructor, which will allocate an array of size 10 A parameterized constructor, which takes a size and use the size to allocate array. A copy constructor, which performs deep copy. A copy assignment operator, which performs deep copy and supports...

  • Write the code for the function that returns a vector containing the out-degrees of all vertices...

    Write the code for the function that returns a vector containing the out-degrees of all vertices given the adjacency list of some directed graph. struct vnode { int v; // vertex                 vnode *next;               vnode(int u, vnode *n) {v = u; next =n;} }; typedef vnode *vnodeptr; vector<int> outdegrees(vector<vnodeptr> adj) {

  • C program that uses pointers as function arguments to do the following: To exemplify pointers, we...

    C program that uses pointers as function arguments to do the following: To exemplify pointers, we will be doing quadratics. Remember that a quadratic expression is of the form: ax2 + bx + c where a. b, c are constant and a is not 0. You will scan in the values a. b. and c. With these values, you will write three functions: quadraticFormula quadraticVertex quadratic Info The first function will perform the quadratic equation to find the roots of...

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