-
Notifications
You must be signed in to change notification settings - Fork 1
/
uva_929.cpp
75 lines (70 loc) · 1.62 KB
/
uva_929.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
#include <bits/stdc++.h>
#define REP(i, a, b) for(int i = a, _b = b; i < _b; ++i)
#define FOR(i, a, b) for(int i = a, _b = b; i <= _b; ++i)
#define endl "\n"
#define puts(_content_) cout << (_content_) << "\n"
#define newline cout << "\n"
using namespace std;
typedef pair<int, int> ii;
const int MX = 1000;
const int INF = 1E9;
int R, C;
int a[MX][MX];
vector<ii> adj[MX*MX];
vector<int> dist;
vector<bool> optimized;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
#ifndef Home
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int tc;
cin >> tc;
while(tc--) {
cin >> R >> C;
REP(r, 0, R) {
REP(c, 0, C) {
cin >> a[r][c];
}
}
// build graph
REP(v, 0, R*C) adj[v].clear();
REP(x, 0, R) {
REP(y, 0, C) {
REP(i, 0, 4) {
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 0 && nx < R && ny >= 0 && ny < C) {
adj[x*C + y].push_back(ii(nx*C + ny, a[nx][ny]));
}
}
}
}
// dijkstra
dist.assign(R*C, INF);
optimized.assign(R*C, false);
dist[0] = a[0][0];
priority_queue<ii, vector<ii>, greater<ii>> que;
que.push(ii(dist[0], 0));
int des = R*C-1;
while(!que.empty()) {
int u = que.top().second; que.pop();
if(optimized[u]) continue;
optimized[u] = true;
if(u == des) break;
for(auto p: adj[u]) {
int w = p.second, v = p.first;
if(dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
que.push(ii(dist[v], v));
}
}
}
cout << dist[des] << endl;
}
return 0;
}