简单的BFS A strange lift

有点疑惑,这个题目用DFS和bfs在时间复杂度上面有什么区别吗?

先把BFS的保存下来,自己写个DFS看下


#include<stdio.h>
#include<string.h>
#define Max 10000
typedef struct node
{
	int step;
	int ceng;
}position;
typedef struct 
{
	int head,tail;
	struct node a[Max];
}queue;
bool visited[205];
void create(queue&);
void enqueue(position,queue&);
position dequeue(queue&);
bool empty(queue&);
int bfs(int ,int ,int ,int []);
int main()
{
	int n,m,v,i,b[205],k;
	while(scanf("%d",&n)&&n)
	{
		memset(visited,0,sizeof(visited));
		scanf("%d %d",&m,&v);
		for(i=1;i<=n;i++)
			scanf("%d",&b[i]);
		if(v==m)
		{
			printf("0\n");
			continue;
		}
		k=bfs(n,m,v,b);
		printf("%d\n",k);
	}
	return 0;
}
int bfs(int n,int m,int v,int b[])
{
	position now,next;
	queue q;
	create(q);
	now.ceng=m;
	now.step=0;
	enqueue(now,q);
	while(!empty(q))
	{
		visited[now.ceng]=true;
		now=dequeue(q);
		next.ceng=now.ceng+b[now.ceng];
		next.step=now.step+1;
		if(next.ceng==v)	return next.step;
		else if(next.ceng<=n&&next.ceng>0&&!visited[next.ceng]) 
		{
			enqueue(next,q);
		}
		next.ceng=now.ceng-b[now.ceng];
		if(next.ceng==v)
		{
			return next.step;
		}
		else if(next.ceng<=n&&next.ceng>00&&!visited[next.ceng])
		{
			enqueue(next,q);
		}
	}
	return -1;
}
void create(queue&q)
{
	q.head=q.tail=0;
}
void enqueue(position p,queue&q)
{
	q.a[q.tail]=p;
	q.tail=(q.tail+1)%Max;
}
position dequeue(queue&q)
{
	position p;
	p=q.a[q.head];
	q.head=(q.head+1)%Max;
	return p;
}
bool empty(queue&q)
{
	if(q.head==q.tail) return true;
	else return false;
}



转载于:https://www.cnblogs.com/yobobobo/archive/2012/05/29/3826838.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值