-
Notifications
You must be signed in to change notification settings - Fork 1
/
0064.cpp
71 lines (55 loc) · 1.79 KB
/
0064.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
class Solution {
public:
int minPathSum2(vector<vector<int>>& grid) {
int w = grid.size();
int h = grid[0].size();
multimap<int, pair<int, int>> next;
next.insert({ grid[0][0], { 0, 0 } });
set<pair<int, int>> done;
vector<vector<int>> cheapest;
cheapest.resize(w);
for (auto& c : cheapest)
c.resize(h);
int iteration = 1;
while (true)
{
auto n = next.begin();
auto cost = n->first;
auto x = n->second.first;
auto y = n->second.second;
cheapest[x][y] = cost;
if (x == w-1 && y == h-1)
return cost;
next.erase(next.begin());
if (done.count({ x, y }) > 0)
continue;
done.insert({ x, y });
if (x < w-1)
next.insert({ cost + grid[x+1][y], { x+1, y } });
if (y < h-1)
next.insert({ cost + grid[x][y+1], { x, y+1 } });
}
return 0;
}
int minPathSum(vector<vector<int>>& grid) {
int h = grid.size();
int w = grid[0].size();
vector<vector<int>> cheapest;
cheapest.resize(h);
for (auto& c : cheapest)
c.resize(w);
cheapest[0][0] = grid[0][0];
for (int x = 0; x < w; x++)
for (int y = 0; y < h; y++)
{
int lowest = 9999999;
if (x > 0)
lowest = grid[y][x] + cheapest[y][x-1];
if (y > 0 && lowest > grid[y][x] + cheapest[y-1][x])
lowest = grid[y][x] + cheapest[y-1][x];
if (x > 0 || y > 0)
cheapest[y][x] = lowest;
}
return cheapest[h-1][w-1];
}
};