1
+ #include " bits/stdc++.h"
2
+ using namespace std ;
3
+
4
+ const pair<int , int > d[] = {{0 , 1 }, {1 , 0 }, {0 , -1 }, {-1 , 0 }};
5
+
6
+ int l, c;
7
+ vector<vector<char >> input;
8
+ vector<vector<int >> st;
9
+
10
+ void compute_weights () {
11
+ priority_queue<tuple<int , int , int >, vector<tuple<int , int , int >>,
12
+ greater<tuple<int , int , int >>>
13
+ q;
14
+ q.push (make_tuple (0 , 1 , 0 ));
15
+ while (!q.empty ()) {
16
+ int ans, x, y;
17
+ tie (ans, x, y) = q.top ();
18
+ q.pop ();
19
+
20
+ // out of bounds
21
+ if (x < 0 || x >= l || y < 0 || y >= c) continue ;
22
+ // not crossable
23
+ if (input[x][y] < ' 0' ) continue ;
24
+
25
+ // already reached this position with a lower score
26
+ ans += input[x][y] - ' 0' ;
27
+ if (st[x][y] <= ans) continue ;
28
+ st[x][y] = ans;
29
+
30
+ for (auto di : d) {
31
+ int dx, dy;
32
+ tie (dx, dy) = di;
33
+ auto next = make_tuple (ans, x + dx, y + dy);
34
+ q.push (next);
35
+ }
36
+ }
37
+ }
38
+
39
+ void print () {
40
+ for (int i = 0 ; i < l; i++) {
41
+ for (int j = 0 ; j < c; j++) {
42
+ cout << setw (10 ) << setfill (' 0' ) << st[i][j] << " " ;
43
+ }
44
+ cout << " \n " ;
45
+ }
46
+ }
47
+
48
+ int main () {
49
+ ios::sync_with_stdio (false );
50
+
51
+ cin >> l >> c;
52
+ input.assign (l, vector<char >(c));
53
+ st.assign (l, vector<int >(c, INT_MAX));
54
+ for (int i = 0 ; i < l; i++) {
55
+ string s;
56
+ cin >> s;
57
+ for (int j = 0 ; j < c; j++) input[i][j] = (s[j] == ' .' ? ' 0' : s[j]);
58
+ }
59
+ compute_weights ();
60
+ // print();
61
+
62
+ cout << st[l - 1 ][c - 2 ];
63
+ }
0 commit comments