Violent search, dfs.
Popularize, improve -.
In other words, the next time I encounter a violent search, I will use bfs to write it.
Details/bugs
-
To open the vis array - to judge whether you have walked or not, reduce the number of times;
-
Clear vis every time you backtrack (both are possible, see the code);
-
The initial value of ans is set to
1e7
(anyway, it is large enough), don't set0x7f
it, this is small enoughint
to only 127; -
It is necessary to judge in the middle whether cnt (the variable passed recursively) has been greater than or equal to ans (the target state has not been reached), and if so, return directly to reduce the number of times and shorten the time.
Commented out is one way to assign vis, not commented out is another way.
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int maxn = 405;
int n, a, b;
int k[maxn], vis[maxn];
int ans, fla;
int sum;
int read ()
{
int x = 1, s = 0;
char ch = getchar ();
while (ch < '0' or ch > '9'){
if (ch == '-') x = -1;
ch = getchar ();
}
while (ch >= '0' and ch <= '9'){
s = s * 10 + ch - '0';
ch = getchar ();
}
return x * s;
}
void dfs (int s, int t, int cnt)
{
if (s == t)
{
fla = 1;
ans = min (ans, cnt);
return;
}
if (cnt >= ans) return;
int de = k[s];
// vis[s] = 1;
if ((s - de) >= 1 and !vis[s - de])
{
vis[s - de] = 1;
dfs (s - de, t, cnt + 1);
vis[s - de] = 0;
}
if ((s + de) <= n and !vis[s + de])
{
vis[s + de] = 1;
dfs (s + de, t, cnt + 1);
vis[s + de] = 0;
}
// vis[s] = 0;
}
signed main ()
{
ans = 1e7;
n = read (), a = read (), b = read ();
for (int i = 1; i <= n; i++) k[i] = read ();
dfs (a, b, 0);
if (ans == 1e7) printf ("-1\n");
else printf ("%lld\n", ans);
return 0;
}