@@ -48,43 +48,36 @@ private void solveCase() throws IOException {
48
48
}
49
49
50
50
51
- Pos p1 = new Pos (0 , 0 , 0 );
51
+ Pos p1 = new Pos (0 , 0 , 0 , k );
52
52
dists [0 ][0 ] = 0 ;
53
53
54
54
PriorityQueue <Pos > pq = new PriorityQueue <>();
55
55
pq .add (p1 );
56
- int ans = Integer . MAX_VALUE ;
56
+ int ans = - 1 ;
57
57
while (!pq .isEmpty ()) {
58
58
Pos p = pq .poll ();
59
59
if (p .x == m - 1 && p .y == n - 1 ) {
60
- ans = Integer .min (ans , p .dist );
60
+ ans = p .dist ;
61
+ break ;
61
62
} else {
62
63
for (int d = 0 ; d < 4 ; d ++) {
63
64
int ndx = p .x + dx [d ];
64
65
int ndy = p .y + dy [d ];
65
- if (ndx >= 0 && ndx < m && ndy >= 0 && ndy < n && grid [ndx ][ndy ] == 0 && dists [ndx ][ndy ] > p .dist + 1 ) {
66
- dists [ndx ][ndy ] = p .dist + 1 ;
67
- Pos np = new Pos (ndx , ndy , p .dist + 1 );
68
- pq .add (np );
69
- }
70
- }
71
- for (int v = 1 ; v <= k ; v ++) {
72
- for (int d = 0 ; d < 4 ; d ++) {
73
- int dv = v + 1 ;
74
- int vdx = p .x + dx [d ] * dv ;
75
- int vdy = p .y + dy [d ] * dv ;
76
- if (vdx >= 0 && vdx < m && vdy >= 0 && vdy < n && grid [vdx ][vdy ] == 0 && dists [vdx ][vdy ] > p .dist + dv ) {
77
- dists [vdx ][vdy ] = p .dist + dv ;
78
- Pos vp = new Pos (vdx , vdy , p .dist + dv );
79
- pq .add (vp );
66
+ if (ndx >= 0 && ndx < m && ndy >= 0 && ndy < n && dists [ndx ][ndy ] > p .dist + 1 ) {
67
+ if (grid [ndx ][ndy ] == 0 ) {
68
+ dists [ndx ][ndy ] = p .dist + 1 ;
69
+ Pos np = new Pos (ndx , ndy , p .dist + 1 , k );
70
+ pq .add (np );
71
+ } else if (p .k > 0 ) {
72
+ dists [ndx ][ndy ] = p .dist + 1 ;
73
+ Pos np = new Pos (ndx , ndy , p .dist + 1 , p .k - 1 );
74
+ pq .add (np );
80
75
}
81
76
}
82
77
}
83
78
}
84
79
}
85
- if (ans == Integer .MAX_VALUE ) {
86
- ans = -1 ;
87
- }
80
+
88
81
out .println (ans );
89
82
}
90
83
@@ -100,11 +93,13 @@ class Pos implements Comparable<Pos> {
100
93
int x ;
101
94
int y ;
102
95
int dist ;
96
+ int k ;
103
97
104
- public Pos (int x , int y , int dist ) {
98
+ public Pos (int x , int y , int dist , int k ) {
105
99
this .x = x ;
106
100
this .y = y ;
107
101
this .dist = dist ;
102
+ this .k = k ;
108
103
}
109
104
110
105
@ Override
0 commit comments