-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.cpp
127 lines (112 loc) · 2.5 KB
/
Graph.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
using namespace std;
#include "Graph.h"
#include <stack>
#include <string>
#include <sstream>
Graph::Graph(int size){
boardSize = size*size +1;
graphArray = new int*[boardSize];
for(int i = 0; i < boardSize; i++){
graphArray[i] = new int[boardSize];
//Sets all the distances to 0
for(int j = 0; j < boardSize; j++)
graphArray[i][j] = 0;
}
//Set row 0 to numbers for ease of use
for(int d = 0; d < boardSize; d++){
graphArray[0][d] = d;
graphArray[d][0] = d;
}
//Set distances for dice roll
for(int k = 1; k < boardSize; k++)
for(int m = k+1; m < k+7; m++)
if(m < boardSize)
graphArray[k][m] = 2;
}
Graph::~Graph(){
for(int i = 0; i <boardSize; i++){
delete[] graphArray[i];
}
delete[] graphArray;
}
int Graph::minDistance(int dist[], bool visit[]){
int min = INT_MAX, min_index;
for(int i = 1; i < boardSize; i++){
if(visit[i] == false && dist[i] <= min){
min = dist[i];
min_index = i;
}
}
return min_index;
}
int Graph::printSolution(int pred[])
{
stringstream path;
stack <int> ordered;
int x = boardSize-1;
ordered.push(x);
while(pred[x] != 0){
ordered.push(pred[x]);
x = pred[x];
}
//NEED TO SUBTRACT LADDERS/SNAKES THAT WERE USED
int size = ordered.size()-1;
while (ordered.empty() != true){
int top = ordered.top();
if(top == 1)
path << top;
else if (graphArray[pred[top]][top] == 1 && pred[top] > top){
path << "-" << top;
size--;
}
else if (graphArray[pred[top]][top] == 1 && pred[top] < top){
path << "+" << top;
size--;
}
else{
path << " " << top;
}
if(ordered.size() == 1)
path << '\n';
ordered.pop();
}
cout << size << endl;
string s = path.str();
cout << s << "";
}
void Graph::dijkstra(){
int distance[boardSize];
bool visited[boardSize];
int pred[boardSize];
for(int i = 1; i < boardSize; i++){
distance[i] = INT_MAX;
visited[i] = false;
}
distance[1] = 0;
pred[1] = 0;
for(int count = 1; count < boardSize-1; count++){
int u = minDistance(distance, visited);
visited[u] = true;
for(int v = 1; v<boardSize; v++)
{
if (!visited[v] && graphArray[u][v] && distance[u] != INT_MAX
&& distance[u]+graphArray[u][v] < distance[v]){
distance[v] = distance[u]+graphArray[u][v];
pred[v] = u;
}
}
}
printSolution(pred);
}
void Graph::print(){
for (int i = 0; i < boardSize; i++){
for (int j = 0; j < boardSize; j++){
cout << graphArray[i][j] << "\t";
}
cout << endl;
}
}