#include #include "linked_list.cpp" // Use the maximum value of int to represent infinity static const int INFINITY=32767; // No cost can be negative, so use -1 to represent a non adjacent vertex static const int NOT_ADJACENT=-1; void main(void) { int n, counter, counter2, adjacent, leastIndex, currentRow, vertex; unsigned cost; Linked_List V, remainingV, output; int **adjacencyMatrix; unsigned **costMatrix; cout << "Enter number of vertices in the graph" << endl; do { cin >> n; } while (n < 1); adjacencyMatrix = new int*[n]; for (counter=0;counter> adjacent; } while (adjacent < -1 || adjacent >= n); if (adjacent == -1) break; cout << "Enter non-negative cost from vertex " << counter << " to vertex " << adjacent << endl; cin >> cost; adjacencyMatrix[adjacent][counter]=cost; } } currentRow=1; // Set the initial values in the matrix // Ask for starting vertex, remove it from V, and add its adjacent values to the cost matrix cout << "Enter starting vertex" << endl; do { cin >> vertex; } while (vertex < 0 || vertex >= n); V.find(vertex); V.del(); // Go through the list of values for the vertex to set the initial values for the cost matrix for (counter=0; counter < n; counter++) { if (adjacencyMatrix[counter][vertex]!=NOT_ADJACENT) { // Fill the array down for (counter2=0; counter2 costMatrix[leastIndex][currentRow-1] + adjacencyMatrix[counter][leastIndex]) { // Fill down for (counter2=currentRow; counter2 < n; counter2++) costMatrix[counter][counter2] = costMatrix[leastIndex][currentRow-1] + adjacencyMatrix[counter][leastIndex]; } } // remove least index from V V.find(leastIndex); V.del(); } cout << "Which vertex do you want to find the cost of reaching?" << endl; // Loop to input vertices while(true) { do { cin >> vertex; } while (vertex < -1 || vertex >=n); if (vertex==-1) break; cout << "Shortest cost is " << costMatrix[vertex][n-1] << endl; currentRow=n-1; output.clear(); output.insert(vertex); // Loop to find path while (true) { while (currentRow>0 && costMatrix[vertex][currentRow] == costMatrix[vertex][currentRow-1]) currentRow--; vertex=costMatrix[n][currentRow]; output.insert(vertex); if (currentRow==0) break; } cout << "Path: "; while (output.size()) cout << output.pop() << " "; cout << endl; cout << "Enter next vertex to find cost of reaching or -1 to stop." << endl; } }