HDOJ 1548 A strange lift (BFS)

http://acm.hdu.edu.cn/showproblem.php?pid=1548

题意:一个电梯,在第 i 层只能选择上或下k [ i ] 层(任何时候都不超过顶楼且不低于1楼),求从A到B层最少要按几下电梯按钮?

思路:BFS

#include<stdio.h>

#define maxn 222

typedef struct
{
	int floor,go,cnt;//floor为当先在的楼层,go为可上、下楼层数,cnt为当前步数
}node;

node quene[maxn], lift[maxn];
int n,a,b;

int bfs()
{
	int front=0,rear=0,now=0,count=0;
	quene[rear++]=lift[a];
	while(front<rear)
	{
		now=quene[front].floor;
		count=quene[front].cnt;
		if(now+quene[front].go<=n&&!lift[now+quene[front].go].cnt)
		{
			lift[now+quene[front].go].cnt=count+1;
			if(b==now+quene[front].go)
				return 1;
			quene[rear++]=lift[now+quene[front].go];
		}
		if(now-quene[front].go>0&&!lift[now-quene[front].go].cnt)
		{
			lift[now-quene[front].go].cnt=count+1;
			if(b==now-quene[front].go)
				return 1;
			quene[rear++]=lift[now-quene[front].go];
		}
		front++;
	}
	return 0;
}

int main()
{
    int i;
    while(scanf("%d",&n)&&n)
    {
        scanf("%d %d",&a,&b);
        for(i=1;i<=n;i++)
		{
            scanf("%d",&lift[i].go);
			lift[i].cnt=0;
			lift[i].floor=i;
		}
        if(a==b)
			printf("0\n");
        else if(bfs())
			printf("%d\n",lift[b].cnt);
		else
			printf("-1\n");
    }
    return 0;
}


你可能感兴趣的:(struct,Go,lift)