《算法笔记》 第八章 提高篇---搜索专题

深度优先算法DFS

代码模板
void DFS(需要记录的一些数值)
{
if(达到临界值)
{
//判断是否为最优并记录最优解
return;
}
//一号分支
(加入剪枝判断)
DFS(选择一号分支各个参数相应的变化);
//二号分支
(加入剪枝判断)
DFS(选择二号分支各个参数相应的变化);

}
背包问题

#include <iostream>
#include <cstdio>
using namespace std;
int n,weight;
int maxvalue=0;
int w[5]={3,5,1,2,2};
int v[5]={4,5,2,1,3};

void DFS(int t,int tw,int tv)
{
	if(t==n)
	{
		if(tv>maxvalue&&tw<=weight)
		{
			maxvalue=tv;
		}
		return;
	}
	DFS(t+1,tw,tv);
	if(tw+w[t]<=weight&&tv+v[t]>tv)
	{
		DFS(t+1,tw+w[t],tv+v[t]);
	}
}

int main() 
{
	scanf("%d%d",&n,&weight);
	DFS(0,0,0);
	printf("%d",maxvalue);
	return 0;
}

广度优先搜索BFS

代码模板
void BFS(int s)
{
queue q;
q.push(s);
while(!q)
{
取出队首元素top;
访问队首元素top;
将队首元素出队;
将top的下一层结点未曾入队的节点全部入队,并设置成已入队
}
}
当需要对队列中的元素进行修改的时候,可以采用入队编号或下标
迷宫问题:

#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
char a[5][5];
int x1[4]={-1,1,0,0};
int y1[4]={0,0,-1,1};
int sign[5][5]={0};

typedef struct node{
	int x;
	int y;
}node;

void BFS(node n1)
{	
	queue<node> p;
	p.push(n1);
	sign[n1.x][n1.y]=1;
	cout<<n1.x<<" "<<n1.y<<endl; 
	while(!p.empty())
	{
		node use=p.front();
		p.pop();
		if(a[use.x][use.y]=='T')
		{
			return;
		}
		for(int i=0;i<4;i++)
		{
			int x2=use.x+x1[i];
			int y2=use.y+y1[i];
			if(a[x2][y2]!='*'&&x2<5&&x2>=0&&y2<5&&y2>=0&&sign[x2][y2]!=1)
			{
				cout<<x2<<" "<<y2<<endl;
				node t;
				t.x=x2;
				t.y=y2;
				p.push(t);
				sign[x2][y2]=1;				
			}
		}
	}
}

int main() 
{
	ios::sync_with_stdio(false);
	for(int i=0;i<5;i++)
	{
		for(int j=0;j<5;j++)
		{
			cin>>a[i][j];
		}
	}
	node n1;
	n1.x=2;
	n1.y=2;
	BFS(n1);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值