-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshortest path
54 lines (48 loc) · 1.91 KB
/
shortest path
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
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
const int rows = 5, cols = 6;
string path[rows][cols];
// Returns the cost of the shortest path from the left to the square in row i, column j.
int calculateCost(int i, int j) {
static int weight[rows][cols] = {{3,4,1,2,8,6},
{6,1,8,2,7,4},
{5,9,3,9,9,5},
{8,4,1,3,2,6},
{3,7,2,8,6,4}};
static int cost[rows][cols] = {};
if (cost[i][j] != 0)
return cost[i][j];
if (j == 0) {
path[i][j] = to_string(i);
return weight[i][j];
}
// Declare the cost matrix.
// If the cost has already been calculated, return it.
// Check for the base case.
// Calculate the costs of the 3 adjacent squares by calling the function recursively
int up = calculateCost((i+rows-1)%rows, j-1);
int left = calculateCost(i, j-1);
int down = calculateCost((i+1)%rows, j-1);
int minCost = min(min(up, left), down);
if (minCost == up)
path[i][j] = path[(i+rows-1)%rows][j-1] + to_string(i);
else if (minCost == left)
path[i][j] = path[i][j-1] + to_string(i);
else
path[i][j] = path[(i+1)%rows][j-1] + to_string(i);
cost[i][j] = minCost + weight[i][j];
return cost[i][j];
}
int main() {
int minRow = 0;
// Call the calculateCost function once for each square in the rightmost column of the grid.
// Check which one has the lowest cost and store the row number in minRow.
for (int i = 1; i < rows; ++i)
if (calculateCost(i, cols-1) < calculateCost(minRow, cols-1))
minRow = i;
cout << "The length of the shortest path is " << calculateCost(minRow, cols-1);
cout << ".\nThe rows of the path from left to right are " << path[minRow][cols-1] << ".";
return 0;
}