Question

***** 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   400
1   10   1200
1   12   900
2   6   120
2   7   110
2   13   700
2   14   600
3   5   30
3   6   50
3   8   450
4   5   50
4   8   300
4   13   350
5   7   40
5   8   100
5   9   475
5   11   650
6   7   60
6   8   195
6   14   80
7   8   65
7   9   425
7   10   700
7   14   325
8   9   325
8   10   600
8   11   700
8   12   550
9   10   60
9   12   400
10   13   200
11   12   125
11   13   400
12   13   350
13   14   700
-1

##Graphs

Min path

DESCRIPTION

Write a program that will display the minimum path between any two vertices in a given graph. The program will input the graph from a file provided by the user. It will prompt the user for entering the name of the start vertex and the end vertex. It will find the minimum path between the two vertices. It will display the minimum path showing all the vertices along the path. It will also display the total distance along the minimum path.

TESTING

Test the program for two data sets included in this module as text files. For each data set, carry out a number of test runs as listed below.

Data Set 1

Test the program for the data set 1 listed. Enter this data into a file and input the data from the file.

The data consists of two parts. In the first part, each line represents a vertex. It contain two values. The first value specifies the vertex number. The second value specifies the vertex name. The first part ends when a line contains -1 by itself. In the second part, each line represents an edge. It contains three values. The first two values specify two vertices connecting the edge. The third value specifies the weight of the edge. This part ends when a line contains -1 by itself.

0 SF

1 LA

2 CHICAGO

3 NY

4 PARIS

5 LONDON

-1

0 1 80

0 2 200

0 3 300

1 2 230

1 5 700

2 3 180

3 4 630

3 5 500

4 5 140

-1

Data Set 1: Test Run 1

Run the program using SF as the start vertex. Program input/output dialog is shown below. The user input is shown in bold.

Enter Start Vertex: SF

Enter End Vertex :LONDON

Min Path: SF LA LONDON 780

Data Set 1: Test Run 2

Enter Start Vertex: SF

Enter End Vertex : PARIS

Min Path: SF LA LONDON PARIS 920

Data Set 2:

Data set 2 is available in a file attached.

For data set 2, run the program several times: each time use the same vertex (the first vertex input) as the start vertex and a different vertex as the destination vertex till each vertex has been used as the destination vertex.

IMPLEMENTATION

MinPath algorithm finds the minimum path from a specified start vertex to a specified target (destination) vertex in a graph and displays the following.

The list of all the vertices in the minimum path from the start vertex to the target vertex.

The total distance from the start vertex to the target vertex along the above path.

Methodology

MinPath algorithm accomplishes the above by using a variation of BreadthFirst traversal algorithm covered in a previous assignment with the following additional provisions.

It uses a priority queue (PmainQ) instead of a regular queue.

In the queue, it enqueues a vertex as an item describing the vertex.  The vertex item contains the following fields:

  • Total Accumulated Distance: The total distance from the start vertex to this vertex.
  • Path List: The list of all vertices in the path from the start vertex to this vertex.  The list of vertices is stored as an array of ints (vertex numbers).
  • Path Length: The length of the above array.

In the priority queue (PmainQ), the vertex items are enqueued in ascending order of the Total Accumulated Distance values in the item vertices.

The item vertices are enqueued and dequeued form the PmainQ using a procedure similar to the BreadthFirst algorithm and is presented below.

You may use the code below as a guidance – but I strongly encourage you to design your own algorithm

  1. Enqueue the start vertex item in the priority queue: PmainQ.
  2. Repeatedly: dequeue a vertex item and enqueue its adjacent vertex items as below

until the target vertex is found or the PmainQ becomes empty.

Dequeue a vertex item.

If (the dequeued vertex item is the target vertex item or PmainQ is empty)

go to step 3

Else

     If it is not previously Marked Visited

Mark it “visited”.

Get a list of all its adjacent vertices.

Enqueue all adjacent vertices that are not previously marked visited into the PMainQ.

Algorithm

//The above methodology is presented below as an algorithm.

Enque the start vertex item in the PmainQ.

While ( !( PmainQ.isEmpty() ) )

{

          Deque a vertex item from the PmainQ.

//Process the vertex item dequeued as follows.

If( vertex is unmarked )

{

          If ( vertex is the target vertex )

                   break from the loop;

Mark the vertex as visited.

//Get a list of all its adjacent vertices by calling a method (say getAdjacent ) as below.

//(Note: getAdjacent returns adjacent vertices in a queue, adjacentQ, passed to it as below).

//(Note: getAdjacent returns vertices in order with the lowest numbered vertex first).                                                                                                           

          getAdjacent (vertex, adjacentQ)

          //Process the adjacent vertices by dequeing them from the adjacent queue

//and enqueueing them in PmainQ as below.

          While ( !( adjacentQ.isEmpty() ) )

          {

                   Dequeue a vertex from adjacentQ.

                   If( adjacent vertex is unmarked )

                   {

                             Enqueue the adjacent vertex item in the PmainQ.

                   }

          }

          }

}

If the target vertex item is found,

      Display the item contents including:

The total distance from the start vertex to the target vertex.

The list of all vertices along the above path.

          Else

     Display message: “Vertex Not Found”.

SUBMIT YOUR SOURSE CODE AND ENOUFG SCREEN SHOTS OF THE OUTPUT PROVING YOUR ALGORITHM IS WORKING

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

PROGRAM:

#include<iostream>

#include<vector>

#include<string>

#include<list>

#include<algorithm>

#include<fstream>

using namespace std;

vector<pair<int, int> > adj[6];

int V = 6;

void addEdge(vector <pair<int, int> > adj[], int u,

int v, int wt)

{

adj[u].push_back(make_pair(v, wt));

adj[v].push_back(make_pair(u, wt));

}

// Print adjacency list representaion ot graph

void printGraph(vector<pair<int, int> > adj[], int V)

{

int v, w;

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

{

cout << u << " - ";

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

{

v = it->first;

w = it->second;

cout << v << " ="

<< w << "\n";

}

cout << "\n";

}

}

// This function mainly does BFS and prints the

// shortest path from src to dest. It is assumed

// that weight of every edge is 1

int findShortestPath(int src, int dest)

{

// Mark all the vertices as not visited

bool *visited = new bool[2 * V];

int *parent = new int[2 * V];

static int total = 0;

// Initialize parent[] and visited[]

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

{

visited[i] = false;

parent[i] = -1;

}

// Create a queue for BFS

list<int> queue;

// Mark the current node as visited and enqueue it

visited[src] = true;

queue.push_back(src);

while (!queue.empty())

{

// Dequeue a vertex from queue and print it

int s = queue.front();

if (s == dest)

return total;

queue.pop_front();

// Get all adjacent vertices of the dequeued vertex s

// If a adjacent has not been visited, then mark it

// visited and enqueue it

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

{

if (!visited[it->first])

{

visited[it->first] = true;

queue.push_back(it->first);

total += it->second;

parent[it->first] = s;

}

}

}

return total;

}

// Driver code

int main()

{

string line;

ifstream myfile("file.txt");

vector<string> vertex;

int count = 1,V;

vector<pair<int, int> > adj[6];

if (myfile.is_open())

{

while (getline(myfile, line))

{

//cout << line << '\n';

while (line != "-1")

{

char *token = strtok(const_cast<char*>(line.c_str()), " ");

token = strtok(NULL, " ");

vertex.push_back(token);

getline(myfile, line);

}

V = vertex.size();

getline(myfile, line);

while (line != "-1")

{

char *token = strtok(const_cast<char*>(line.c_str()), " ");

int u = atoi(token);

int v = atoi(strtok(NULL, " "));

int w = atoi(strtok(NULL, " "));

addEdge(adj, u, v, w);

getline(myfile, line);

}

}

myfile.close();

}

else cout << "Unable to open file";

string start, end;

cout << "Enter Start Vertex : ";

cin >> start;

cout << "Enter End Vertex : ";

cin >> end;

int s, e;

int i = 0;

for (auto it = vertex.begin(); it != vertex.end(); it++)

{

if (*it == start) s = i;

if (*it == end) e = i;

i++;

}

cout << findShortestPath(s, e) << endl;

printGraph(adj, V);

system("pause");

return 0;

}

Add a comment
Know the answer?
Add Answer to:
***** running late, mere 3 hours left for due time, please help ** #needed in c++...
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
  • from collections import defaultdict    # This class represents a directed graph using # adjacency list...

    from collections import defaultdict    # This class represents a directed graph using # adjacency list representation class Graph:        # Constructor     def __init__(self):            # default dictionary to store graph         self.graph = defaultdict(list)        # function to add an edge to graph     def addEdge(self,u,v):         self.graph[u].append(v)        # Function to print a BFS of graph     def BFS(self, s):            # Mark all the vertices as not visited         visited = [False] * (len(self.graph))            # Create a queue for BFS         queue...

  • (5 marks) a. The pseudo-code for breadth-first search, modified slightly from Drozdek,1 is as follows: void...

    (5 marks) a. The pseudo-code for breadth-first search, modified slightly from Drozdek,1 is as follows: void breadthFirstSearch (vertex w) for all vertices u num (u) 0 null edges i=1; num (w) i++ enqueue (w) while queue is not empty dequeue ( V= for all vertices u adjacent to v if num(u) is 0 num (u) = i++; enqueue (u) attach edge (vu) to edges; output edges; Now consider the following graph. Give the breadth-first traversal of the graph, starting from...

  • Programming Traversal Methods in C++ (depth first & breadth first) Need solution ASAP any help is...

    Programming Traversal Methods in C++ (depth first & breadth first) Need solution ASAP any help is much appreciated. read a set of data representing a directed, unweighted graph build an in-memory graph structure using the data display the graph using depth-first traversal display the graph using breadth-first traversal Input data - The data consists of records like this: 16 3 15 4 -1 This represents a vertex 16 with neighbors 3, 15, and 4. The -1 is the indicator that...

  • HI USING C++ CAN YOU PLEASE PROGRAM THIS ASSIGNMENT AND ADD COMMENTS: stackARRAY: #include<iostream> #define SIZE...

    HI USING C++ CAN YOU PLEASE PROGRAM THIS ASSIGNMENT AND ADD COMMENTS: stackARRAY: #include<iostream> #define SIZE 100 #define NO_ELEMENT -999999 using namespace std; class Stack { int arr[SIZE]; // array to store Stack elements int top; public: Stack() { top = -1; } void push(int); // push an element into Stack int pop(); // pop the top element from Stack int topElement(); // get the top element void display(); // display Stack elements from top to bottom }; void Stack...

  • Creating a simple graph in C++; need solution ASAP. EDIT: Pls comment letting me know what...

    Creating a simple graph in C++; need solution ASAP. EDIT: Pls comment letting me know what other information you need rather than just "..." Thank you. Here is the assignment: In this final practice problem, you’ll: read a set of data representing a directed, unweighted graph build an in-memory graph structure using the data display the graph using depth-first traversal display the graph using breadth-first traversal Input data - The data consists of records like this: 16 3 15 4...

  • I have a Graph.java which I need to complete four methods in the java file: completeGraph(),...

    I have a Graph.java which I need to complete four methods in the java file: completeGraph(), valence(int vid), DFS(int start), and findPathBFS(int start, int end). I also have a JUnit test file GraphTest.java for you to check your code. Here is Graph.java: import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; /* Generic vertex class */ class Vertex<T> { public T data; public boolean visited; public Vertex() { data = null; visited = false; } public Vertex(T _data) { data =...

  • Writing a program in C please help!! My file worked fine before but when I put...

    Writing a program in C please help!! My file worked fine before but when I put the functions in their own files and made a header file the diplayadj() funtion no longer works properly. It will only print the vertices instead of both the vertices and the adjacent like below. example input form commnd line file: A B B C E X C D A C The directed edges in this example are: A can go to both B and...

  • Please answer A and B 1. Consider the following adjacency matrix representing vertices v through v^:...

    Please answer A and B 1. Consider the following adjacency matrix representing vertices v through v^: weighted graph containing a ro 5 0 0 8 0 61 5 0 0 7 0 0 0 jo 0 0 0 0 1 3| 0 7 0 0 2 0 0 8 0 0 0 0 1 0 0 0 4 L6 0 3 0 0 4 0- 20 0 0 a. Draw the graph resulting from the adjacency matrix b. Assuming the...

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

  • Radix sort C++ Come up with an unsorted array of numbers (integer array). Sort the numbers...

    Radix sort C++ Come up with an unsorted array of numbers (integer array). Sort the numbers in ascending order and descending order and display them using radix sort. First sort in ascending, then reset the array to its original order and finally sort the array again in descending order. USE THIS STUCTURE struct nodeQ{                            node *front;                            node *rear;               };               nodeQ que[10]; enqueue(que[i],data); EXAMPLE: Original, unsorted list: [170, 45, 75, 90, 2, 802, 24, 66] 1ST PASS:...

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