-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem083.cpp
127 lines (115 loc) · 2.82 KB
/
problem083.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 <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <queue>
using namespace std;
struct Node
{
int x, y, cost, dist;
Node(int _x, int _y, int _cost)
{
x = _x;
y = _y;
cost = _cost;
dist = -1;
}
};
struct CompareCost
{
bool operator()(Node const& l, Node const& r)
{
return l.dist > r.dist;
}
};
int main()
{
ifstream fin("problem083.txt");
vector<vector<Node> > nodes;
string delim = ",";
string line;
while (getline(fin, line))
{
vector<Node> row;
int pos = 0;
int x = 0;
while ((pos = line.find(delim)) != std::string::npos)
{
int cost = atoi(line.substr(0, pos).c_str());
row.push_back(Node(x, nodes.size(), cost));
line.erase(0, pos + delim.size());
x++;
}
int cost = atoi(line.c_str());
row.push_back(Node(x, nodes.size(), cost));
nodes.push_back(row);
}
fin.close();
int bestResult = -1;
// Dijkstra
for (int j = 0; j < nodes.size(); j++)
{
for (int k = 0; k < nodes.size(); k++)
{
nodes[j][k].dist = -1;
}
}
std::priority_queue<Node, vector<Node>, CompareCost> pq;
Node source = nodes[0][0];
nodes[0][0].dist = source.cost;
source.dist = source.cost;
pq.push(source);
while (!pq.empty())
{
Node u = pq.top();
if (u.x == nodes.size() - 1 && u.y == nodes.size() - 1)
{
cout << u.dist << endl;
break;
}
pq.pop();
if (u.dist == -1)
break;
if (u.y > 0)
{
Node v = nodes[u.y - 1][u.x];
if (v.dist == -1 || u.dist + v.cost < v.dist)
{
nodes[v.y][v.x].dist = u.dist + v.cost;
v.dist = u.dist + v.cost;
pq.push(v);
}
}
if (u.y < nodes.size() - 1)
{
Node v = nodes[u.y + 1][u.x];
if (v.dist == -1 || u.dist + v.cost < v.dist)
{
nodes[v.y][v.x].dist = u.dist + v.cost;
v.dist = u.dist + v.cost;
pq.push(v);
}
}
if (u.x > 0)
{
Node v = nodes[u.y][u.x - 1];
if (v.dist == -1 || u.dist + v.cost < v.dist)
{
nodes[v.y][v.x].dist = u.dist + v.cost;
v.dist = u.dist + v.cost;
pq.push(v);
}
}
Node v = nodes[u.y][u.x + 1];
if (v.dist == -1 || u.dist + v.cost < v.dist)
{
nodes[v.y][v.x].dist = u.dist + v.cost;
v.dist = u.dist + v.cost;
pq.push(v);
}
}
return 0;
}