又是一道被折磨致死的题。。调了我两个多小时。。到最后发现题意理解错了!!!!BFS搜索的时候的步数不是固定的,而是搜索到当前块上的grid数字,我把他理解成每次固定的了。。结果导致无限WA。。还有一个容易错的地方是逆时针搜的时候下标的确定,一定要保证下标在0到n内,具体看代码吧。。300出头第一题就这么坑,唉。。
#include<stdio.h>
#include<string.h>
#include<limits.h>
static int a[100];
static void bfs(int *time, int start, int n)
{
int queue[200], begin = 0, end = 0;
queue[end++] = start;
while (begin != end)
{
int now = queue[begin++];
int next = ((now - a[now]) % n + n) % n;
if (time[next] == -1)
{
time[next] = time[now] + 1;
queue[end++] = next;
}
next = (now + a[now]) % n;
if (time[next] == -1)
{
time[next] = time[now] + 1;
queue[end++] = next;
}
}
}
int main()
{
int n;
while (scanf("%d", &n), n)
{
int i, from, to;
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
scanf("%d %d", &from, &to);
int timef[100], timet[100];
memset(timef, -1, sizeof(timef));
memset(timet, -1, sizeof(timet));
timef[from] = 0;
timet[to] = 0;
bfs(timef, from, n);
bfs(timet, to, n);
int mint = INT_MAX;
for (i = 0; i < n; i++)
if (timef[i] != -1 && timet[i] != -1 && timef[i] + timet[i] < mint)
mint = timef[i] + timet[i];
if (mint == INT_MAX)
puts("Lara is traped!");
else
printf("open it on the %dth move!\n", mint);
}
return 0;
}