【图论--搜索篇】宽度优先搜索,广度优先搜索


今日语录: 成功是一种心态,如果你相信自己能做到,那你已经迈出成功的第一步。

文章目录

宽度优先搜索(bfs)

cpp 复制代码
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>

//深度优先搜索DFS

using namespace std;
typedef pair<int, int> PII;

const int N = 110;

int n,m;
char g[N][N];
bool d[N][N];
PII q[N * N];

int bfs()
{
	int hh = 0, tt = 0;
	q[0] = { 0,0 };

	memset(d, -1, sizeof d);
	d[0][0] = 0;

	int dx[4] = { -1,0,1,0 }, dy[4] = { 0,1,0,-1 };

	while (hh < tt)
	{
		auto t = q[hh++];

		for (int i = 0; i < 4; i++)
		{
			int x = t.first + dx[i], y = t.second + dy[i];
			if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1)
			{
				d[x][y] = d[t.first][t.second] + 1;
				q[++tt] = { x,y };
			}
		}
	}
	return d[n - 1][m - 1];
}

int main()
{
	cin >> n >> m;

	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			cin >> g[i][j];

	cout << bfs() << endl;
	
	return 0;
}

广度优先搜索(dfs)

cpp 复制代码
//数字全排序
#include <iostream>

using namespace std;

const int N = 10;

int n;
int path[N];  // 用于存储当前排列的数组
bool st[N];   // 标记数组,用于标记数字是否已经被使用过

void dfs(int u)
{
    // 当前排列已经生成完成
    if (u == n)
    {
        for (int i = 0; i < n; i++)
            printf("%d", path[i]);
        puts(" ");  // 输出当前排列
        return;
    }

    // 从1到n尝试每个数字
    for (int i = 1; i <= n; i++)
        if (!st[i])  // 如果数字i没有被使用过
        {
            path[u] = i;  // 将数字i加入当前排列
            st[i] = true;  // 标记数字i为已使用
            dfs(u + 1);    // 递归生成下一个位置的数字
            st[i] = false; // 恢复现场,将数字i标记为未使用
        }
}

int main()
{
    cin >> n;  // 输入排列的长度n
    dfs(0);    // 从第0个位置开始生成排列
    return 0;
}
相关推荐
m0_748708057 分钟前
C++中的观察者模式实战
开发语言·c++·算法
然哥依旧7 分钟前
【轴承故障诊断】基于融合鱼鹰和柯西变异的麻雀优化算法OCSSA-VMD-CNN-BILSTM轴承诊断研究【西储大学数据】(Matlab代码实现)
算法·支持向量机·matlab·cnn
qq_5375626719 分钟前
跨语言调用C++接口
开发语言·c++·算法
Tingjct31 分钟前
【初阶数据结构-二叉树】
c语言·开发语言·数据结构·算法
C雨后彩虹32 分钟前
计算疫情扩散时间
java·数据结构·算法·华为·面试
yyy(十一月限定版)1 小时前
寒假集训4——二分排序
算法
星火开发设计1 小时前
类型别名 typedef:让复杂类型更简洁
开发语言·c++·学习·算法·函数·知识
醉颜凉1 小时前
【LeetCode】打家劫舍III
c语言·算法·leetcode·树 深度优先搜索·动态规划 二叉树
达文汐2 小时前
【困难】力扣算法题解析LeetCode332:重新安排行程
java·数据结构·经验分享·算法·leetcode·力扣
一匹电信狗2 小时前
【LeetCode_21】合并两个有序链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl