題目鏈接:傳送門
一個水題,不過我dfs還是不太行,wa了兩次
這題可以用DFS和BFS寫,另外也可以建圖跑最短路。下面放雙搜代碼:
BFS:
int a[210];
int A, B;
bool vis[210];
int n;
int ff = -1;
struct node
{
int now, ans;
};
queue<node> q;
void bfs()
{
while (q.size())
{
node temp = q.front();
q.pop();
vis[temp.now] = 1;
if (temp.now == B)
{
ff = temp.ans;
return;
}
if (temp.now + a[temp.now] <= n && vis[temp.now + a[temp.now]] == 0)
q.push(node{temp.now + a[temp.now], temp.ans + 1});
if (temp.now - a[temp.now] >= 1 && vis[temp.now - a[temp.now]] == 0)
q.push(node{temp.now - a[temp.now], temp.ans + 1});
}
}
int main()
{
cin >> n >> A >> B;
for (int i = 1; i <= n; i++)
cin >> a[i];
q.push(node{A, 0});
bfs();
cout << ff << endl;
return 0;
}
DFS
int a[210];
int A, B;
bool vis[210];
int n;
int ff = INF;
void dfs(int now, int ans)
{
if (ans > ff) //剪枝
return;
vis[now] = 1;
if (now == B)
{
ff = min(ff, ans);
vis[now] = 0; //回溯記得解標
return;
}
int x = now + a[now];
int y = now - a[now];
if (x <= n && !vis[x])
dfs(x, ans + 1);
if (y >= 1 && !vis[y])
dfs(y, ans + 1);
vis[now] = 0;
}
int main()
{
// fre;
cin >> n >> A >> B;
for (int i = 1; i <= n; i++)
cin >> a[i];
dfs(A, 0);
if (ff == INF)
cout << -1 << endl;
else
cout << ff << endl;
return 0;
}