Question

You need to start doing your CST370 homework, but you don't really feel like it. You...

You need to start doing your CST370 homework, but you don't really feel like it. You decide
to take the longest route from your current location on campus to where you plan to do
your homework to procrastinate a bit. You're given a graph representing CSUMB's campus,
and your goal is to nd the path with the most stops to your homework destination without
visiting any location more than once.

Input
• The first line contains your current location.
• The second line contains the location where you'll do your homework.
• The remaining input describes a graph where each edge means two locations are adjacent.
{ The next line contains an integer n, the number of locations on campus.
{ The next n lines each contain one location. This makes up an array of verticies.
{ The next line contains two space-separated integers: n e
{ The next e lines each contain two space-separated integers a and b describing an
edge from the vertex indexed at a to the vertex indexed at b.
Constraints
You can assume the campus locations form a connected, undirected graph. The graph is connected and undirected.
Output
The length of the longest possible path you can take your current location to your homework
destination on a single line.

How do you solve this problem with breadth first search in C++?

Sample Input:

BIT
East Campus
9
Pool
Library
Gym
BIT
Construction Site
Student Center
East Campus
VPA Building
Otter Express
9 22
0 2
0 4
1 3
1 4
2 0
2 8
3 4
3 1
3 8
3 5
4 3
4 1
4 0
5 8
5 3
6 7
7 6
7 8
8 5
8 3
8 2
8 7

Sample Output:

7

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

# Please leave a thumbs up.

The problem of finding longest path between any two vertices of a graph is the NP Hard problem.

Also, simple way to do this is to use adjency matrix or adjency list.

Also, you can use floyd warshall algorithm that uses dynamic programming to find shortest path and tweak some parts of it to find longest path between two vertices.

Heres a code to find the longest path in your grapgh.

// C++ program to find longest path

#include <bits/stdc++.h>

#include<string.h>

using namespace std;

  

// This class represents a undirected graph using adjacency list

class Graph

{

    int V;              // No. of vertices

    list<int> *adj;     // Pointer to an array containing

                        // adjacency lists

public:

    Graph(int V);              // Constructor

    void addEdge(int v, int w);// function to add an edge to graph

    void longestPathLength(); // prints longest path of the tree

    pair<int, int> bfs(int u); // function returns maximum distant

                               // node from u with its distance

};

  

Graph::Graph(int V)

{

    this->V = V;

    adj = new list<int>[V];

}

  

void Graph::addEdge(int v, int w)

{

    adj[v].push_back(w);    // Add w to v’s list.

    adj[w].push_back(v);    // Since the graph is undirected

}

  

// method returns farthest node and its distance from node u

pair<int, int> Graph::bfs(int u)

{

    // mark all distance with -1

    int dis[V];

    memset(dis, -1, sizeof(dis));

  

    queue<int> q;

    q.push(u);

  

    // distance of u from u will be 0

    dis[u] = 0;

  

    while (!q.empty())

    {

        int t = q.front();       q.pop();

  

        // loop for all adjacent nodes of node-t

        for (auto it = adj[t].begin(); it != adj[t].end(); it++)

        {

            int v = *it;

  

            // push node into queue only if

            // it is not visited already

            if (dis[v] == -1)

            {

                q.push(v);

  

                // make distance of v, one more

                // than distance of t

                dis[v] = dis[t] + 1;

            }

        }

    }

  

    int maxDis = 0;

    int nodeIdx;

  

    // get farthest node distance and its index

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

    {

        if (dis[i] > maxDis)

        {

            maxDis = dis[i];

            nodeIdx = i;

        }

    }

    return make_pair(nodeIdx, maxDis);

}

  

// method prints longest path of given tree

int Graph::longestPathLength(int s)

{

    pair<int, int> t1, t2;

  

    // first bfs to find one end point of

    // longest path

    t1 = bfs(s);

  

    // second bfs to find actual longest path

    t2 = bfs(t1.first);

  

return t2.second;

}

  

// Driver code to test above methods

int main()

{

string myLocation;

cin>>myLocation;

string dest;

cin>>dest;

int totalLocations;

cin>>totalLocations;

for(int i=0;i<totalLocations;i++){

string loc;

cin>>loc;// here each location is represented by numbers ex pool=0,library=2 and so on.

}

    // Create a graph given in the example

int TotalLoc;

cin>>TotalLoc;

int totaledges;

cin>>totaledges;

    Graph g(totalLocations);

for(i=0;i<totaledges;i++){

int v1;

cin>>v1;

int v2;

cin>>v2;

    g.addEdge(v1, v2);

}

  

int length= g.longestPathLength();

cout<<length;

    return 0;

}

Add a comment
Know the answer?
Add Answer to:
You need to start doing your CST370 homework, but you don't really feel like it. You...
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
  • 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...

  • In C++ Design a format for storing graphs in files. This will store your graph into a file with t...

    in C++ Design a format for storing graphs in files. This will store your graph into a file with the following requirements: The first line will contain the number of Vertices. The second line will have a ‘U’ or a ‘D’ to tell the system if it is Undirected or Directed. The rest of the lines will be here for each of the edges. Each edge will contain three pieces of information: An integer containing the first Vertex An integer...

  • a. You have 5 problems in this assignment. b. G++ compiler will be used to compile...

    a. You have 5 problems in this assignment. b. G++ compiler will be used to compile your source codes. c. Your program will be tested on Ubuntu 16.04. d. You are not allowed to use global variables in your implementation. e. Your program will get two arguments, input and output file names, from the command line: >> Your_Executable INPUT_FILE_NAME OUTPUT_FILE_NAME 1. Given a number ? , we initially have ?+1 different sets which are {0}, {1}, {2}, ... , {?}....

  • Hello, i need help with this homework: Code provided: public class DirectedWeightedExampleSlide18 { public static void...

    Hello, i need help with this homework: Code provided: public class DirectedWeightedExampleSlide18 { public static void main(String[] args) { int currentVertex, userChoice; Scanner input = new Scanner(System.in); // create graph using your WeightedGraph based on author's Graph WeightedGraph myGraph = new WeightedGraph(4); // add labels myGraph.setLabel(0,"Spot zero"); myGraph.setLabel(1,"Spot one"); myGraph.setLabel(2,"Spot two"); myGraph.setLabel(3,"Spot three"); // Add each edge (this directed Graph has 5 edges, // so we add 5 edges) myGraph.addEdge(0,2,9); myGraph.addEdge(1,0,7); myGraph.addEdge(2,3,12); myGraph.addEdge(3,0,15); myGraph.addEdge(3,1,6); // let's pretend we are on...

  • 8. For each of the following, either draw a undirected graph satisfying the given criteria or explain why it cannot be done. Your graphs should be simple, i.e. not having any multiple edges (more tha...

    8. For each of the following, either draw a undirected graph satisfying the given criteria or explain why it cannot be done. Your graphs should be simple, i.e. not having any multiple edges (more than one edge between the same pair of vertices) or self-loops (edges with both ends at the same vertex). [10 points] a. A graph with 3 connected components, 11 vertices, and 10 edges. b. A graph with 4 connected components, 10 vertices, and 30 edges. c....

  • Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, ...

    Help !! I need help with Depth-First Search using an undirected graph. Write a program, IN JAVA, to implement the depth-first search algorithm using the pseudocode given. Write a driver program, which reads input file mediumG.txt as an undirected graph and runs the depth-first search algorithm to find paths to all the other vertices considering 0 as the source. This driver program should display the paths in the following manner: 0 to ‘v’: list of all the vertices traversed to...

  • Problem definition: Give the program that implement Prim’s algorithm. Input: First line is N, denotes the...

    Problem definition: Give the program that implement Prim’s algorithm. Input: First line is N, denotes the amount of test case, then there are Ns graph data with an option number (determine whether output the selected edges or not). Each graph is undirected and connected, it is composed of V (the number of vertices, <= 1000), E (the number of edges, <=10000), then followed by Es edges which are denoted by pair of vertex and weight (e.g., 2 4 10 means...

  • ***** running late, mere 3 hours left for due time, please help ** #needed in c++...

    ***** running late, mere 3 hours left for due time, please help ** #needed in c++ #inputfile MinPath2.txt 0   SF 1   LA 2   DALLAS 3   CONCORD 4   PHOENIX 5   CHICAGO 6   ST LOUIS 7   BOSTON 8   NY 9   LONDON 10   PARIS 11   TOKYO 12   BANGKOK 13   MEXICO CITY 14   MONTREAL -1   0   1   40 0   2   100 0   4   130 0   8   200 0   9   800 0   10   900 1   2   50 1   3   80 1   4   70 1   8  ...

  • Please write your answer clearly and easy to read. Please only answer the ones you can....

    Please write your answer clearly and easy to read. Please only answer the ones you can. I will upvote all the submitted answers. Question 5. Prove by contradiction that every circuit of length at least 3 contains a cycle Question 6. Prove or disprove: There exists a connected graph of order 6 in which the distance between any two vertices is even Question 7. Prove formally: If a graph G has the property that every edge in G joins a...

  • write the solution of the program by python 3 language : I need the program using...

    write the solution of the program by python 3 language : I need the program using list or string or loops (while and for) or if,elif,else : You are given a sequence of n non-zero integers a1,a2,…,an. Determine if the given sequence contains a pair of adjacent elements of the same sign (both negative or both positive). Two elements are called adjacent if they stand next to each other in the sequence. Input The first line contains an integer n...

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