《算法笔记》学习笔记(15):BFS和DFS

《算法笔记》学习笔记(15):BFS和DFS

很久没有更新《算法笔记》的内容了,STL库除了vector之外的容器都不是很复杂书中第七章介绍的栈、队列和链表的应用在以前学习数据结构时学习过,所以只对我掌握不太好的DFS和BFS做一下笔记。

DFS

DFS(Depth First Serach),深度优先搜索就是在每次搜索时往最深的哪一条路走,若不行再回到上一个节点。其过程类似于栈的出入。一般使用递归就可以实现DFS。

背包问题

问题

有n件物品,每件的重量为w[i],价值为c[i],给定背包的容量V,要求选出满足条件时最大的价值。

思路

每次都要对物品选择,那么DFS函数应该为

void DFS(int index,int sumW,int sumC)

其中,index为当前处理物品的编号,sumW为当前重量总和,sumC为当前价值总和。对于每个物品,都有选和不选两种做法,,所以在DFS中会有两条岔路

void DFS(int index, int sumW, int sumC)
{
	if (index == n)
	{
		return;
	}//已完成n件物品的选择,返回
	DFS(index + 1, sumW, sumC);//不选该物品的岔路
	if (sumW + w[index] <= V)//如果该物品加入后重量在允许范围内
	{
		if (sumC + c[index] > maxValue)//加入后的总价值比之前的最大值要大
		{
			maxValue = sumC + c[index];//替换最大值
		}
		DFS(index + 1, sumW + w[index], sumC + c[index]);//选择该物品的岔路
	}
}

以上代码中通过条件来限制DFS的操作称为剪枝

完整代码

#define _CRT_SECURE_NO_WARNINGS 1
#include<cstdio>
const int maxn = 30;
int n, V, maxValue = 0;
int w[maxn], c[maxn];
void DFS(int index, int sumW, int sumC)
{
	if (index == n)
	{
		return;
	}
	DFS(index + 1, sumW, sumC);
	if (sumW + w[index] <= V)
	{
		if (sumC + c[index] > maxValue)
		{
			maxValue = sumC + c[index];
		}
		DFS(index + 1, sumW + w[index], sumC + c[index]);
	}
}

int main()
{
	scanf("%d%d", &n, &V);
	for (int i = 0; i < n; i++)
	{
		scanf("%d", &w[i]);
	}
	for (int i = 0; i < n; i++)
	{
		scanf("%d", &c[i]);
	}
	DFS(0, 0, 0);
	printf("%d\n", maxValue);
	return 0;
}

选数问题

问题

给定N个整数,选择K个数,使这K个数的和等于X,且平方和最大。

思路

对于这题,我们需要一个参数nowK记录当前已选择的数的个数,sum记录当前已选数的和,sumSqu记录当前已选数的平方和,那么DFS函数就可以写作

void DFS(int index,int nowK,int sum,int sumSqu)

另外,我们需要设置一个数组temp(可用vector)用于存放临时方案,选index号数分支中,就将A[index]加入temp中,分支结束时将其去除。设置一个存放结果的数组ans,每当选择的数满足条件且sumSqu大于当前的最大sumSqu时,将temp的值赋给ans。

完整代码

#define _CRT_SECURE_NO_WARNINGS 1
#include<cstdio>
#include<vector>

using namespace std;

//平方和可能为0,所以初始值为-1 
int n, a[100], x, s, maxSumSqu = -1;//n为总个数,x为要选的个数,s为要求的和
vector<int> tmp, out;

void dfs(int index, int nowX, int sum, int sumSqu)
{
	//当满足题目条件 
	if (nowX == x && sum == s)
	{
		if (sumSqu > maxSumSqu)
		{
			maxSumSqu = sumSqu; //更新最大平方和 
			out = tmp; //更新最优方案 
		}
		return;
	}
	//这个判断不能放在第一步,因为index==n就return可能会错过最佳方案的更新 
	if (index == n || nowX > x || sum > s) return;
	//选index号数 
	tmp.push_back(a[index]); //记录当前数字a[index] 
	dfs(index + 1, nowX + 1, sum + a[index], sumSqu + a[index] * a[index]);
	//不选index号数 
	tmp.pop_back(); //删除数字a[index] 
	dfs(index + 1, nowX, sum, sumSqu);
}

int main()
{
	int i;
	scanf("%d%d%d", &n, &x, &s);
	for (i = 0; i < n; i++)
		scanf("%d", &a[i]);
	dfs(0, 0, 0, 0);
	for (i = 0; i < out.size(); i++)
		printf("%d ", out[i]);
	return 0;
}

总结

总的来说,在解决DFS类的题时,要找到分出的几条岔路和结束的条件,并做相应的剪枝,用递归完成算法

BFS

BFS(breadth first search),广度优先搜索在每次搜索时等会先访问玩同一层的节点,在对某个节点的下一层的所有节点访问,类似于队列的出入操作。

模板

BFS可用queue来实现,其解题模板为

void BFS(int s)
{
	queue<int>q;
	q.push(s);
	while(!q.empty())
	{
	取出队首元素top;
	访问队首元素top;
	将队首元素出队;
	将top的下一层结点中未曾入队的结点全部入队,并设置状态为已入队;
	}
}

求块问题

问题

给出m*n矩阵,元素为0或1,若矩阵中有若干个1相邻,则称之为块。求给定矩阵中的块数。

思路

按照上述的模板,对每一个位置访问,为0则跳过,为1则使用BFS判断周围4个位置,不断循环。同时设置一个bool型矩阵inq记录某一位置是否已入过队,若已入过队则不需要访问,这一步主要是防止走回头路。
访问周围4个位置时,可以用一个trick,即设置两个增量数组

int X[]={0,0,1,-1};
int Y[]={1,-1,0,0};

再做一个循环,使x和y分别加上数组中对应的值即可实现。

完整代码

#define _CRT_SECURE_NO_WARNINGS 1
#include<cstdio>
#include<queue>
using namespace std;
const int maxn = 100;
struct node
{
	int x, y;
}Node;
int n, m;//矩阵的大小为n*m
int matrix[maxn][maxn];
bool inq[maxn][maxn] = { false };//判断某一点是否进入过队列的数组
int X[4] = { 0,0,1,-1 };
int Y[4] = { 1,-1,0,0 };
//判断是否需要访问
bool judge(int x, int y)
{
	if (x >= n || x < 0 || y >= m || y < 0)return false;//超出矩阵范围的返回false
	if (matrix[x][y] == 0 || inq[x][y] == true)return false;//值为0或已经进过队列的返回false
	return true;
}

void BFS(int x, int y)
{
	queue<node>Q;
	Node.x = x;
	Node.y = y;
	Q.push(Node);
	inq[x][y] = true;//标记已入过队
	while (!Q.empty())
	{
		node top = Q.front();
		Q.pop();
		for (int i = 0; i < 4; i++)
		{
			int newX = top.x + X[i];
			int newY = top.y + Y[i];
			if (judge(newX, newY))
			{
				Node.x = newX;
				Node.y = newY;
				Q.push(Node);
				inq[newX][newY] = true;
			}
		}
	}
}

int main()
{
	scanf("%d%d", &n, &m);
	for (int x = 0; x < n; x++)
	{
		for (int y = 0; y < m; y++)
		{
			scanf("%d", &matrix[x][y]);
		}
	}
	int ans = 0;//结果
	for (int x = 0; x < n; x++)
	{
		for (int y = 0; y < m; y++)
		{
			if (matrix[x][y] == 1 && inq[x][y] == false)
			{
				ans++;
				BFS(x, y);//访问整个块,将所有为1的位置在inq中设为true
			}
		}
	}
	printf("%d\n", ans);
	return 0;
}

迷宫问题

问题

给定一个nm的迷宫,用“."表示可以通过的道路,””表示墙壁,S表示起点,T表示终点。求起点到终点的最少步数。

思路

与上题类似,,只需多设一个步数的属性即可

完整代码

#define _CRT_SECURE_NO_WARNINGS 1
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 100;
struct node
{
	int x, y;
	int step;//从起点S到该位置的步数
}S,T,Node;//起点、终点、temp
int n, m;//行、列
char maze[maxn][maxn];//迷宫数组
bool inq[maxn][maxn] = { false };//记录是否入过队的数组
int X[4] = { 0,0,1,-1 };
int Y[4] = { 1,-1,0,0 };//偏移数组

bool test(int x, int y)
{
	if (x >= n || x < 0 || y >= m || y < 0)return false;//不在迷宫内返回false
	if (maze[x][y] == '*')return false;//墙壁返回false
	if (inq[x][y] == true)return false;//已入过队返回false
	return true;
}

int BFS()
{
	queue<node>q;//创建队列
	q.push(S);//起点入队
	//队列不空则进行BFS
	while (!q.empty())
	{
		node top = q.front();//top为队首元素
		q.pop();//队首元素出队
		if (top.x == T.x && top.y == T.y)
		{
			return top.step;//若在终点则返回步数
		}
		for (int i = 0; i < 4; i++)//对该点的上下左右点判断
		{
			int newX = top.x + X[i];
			int newY = top.y + Y[i];
			if (test(newX, newY))//如果需要访问
			{
				Node.x = newX, Node.y = newY;
				Node.step = top.step + 1;//改变步数
				q.push(Node);//入队
				inq[newX][newY] = true;//标记已入过队
			}
		}
	}
	return -1;//无法找到终点
}

int main()
{
	scanf("%d%d", &n, &m);//输入迷宫大小
	for (int i = 0; i < n; i++)
	{
		getchar();//过滤每行后面的换行符
		for (int j = 0; j < m; j++)
		{
			maze[i][j] = getchar();
		}
		maze[i][m + 1] = '\0';
	}
	scanf("%d%d%d%d", &S.x, &S.y, &T.x, &T.y);//输入终点和起点坐标
	S.step = 0;
	printf("%d\n", BFS());
	return 0;
}

总结

对于BFS的题目,只需按照上述的模板进行BFS操作即可。
还需注意的是,queue中的元素是原本元素的一份副本,改变queue中的元素值对本来的元素没有影响,反之亦然。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值