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


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

文章目录

宽度优先搜索(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;
}
相关推荐
zstar-_19 小时前
【不背八股】12.十大排序算法
数据结构·算法·排序算法
吃着火锅x唱着歌19 小时前
LeetCode 2110.股票平滑下跌阶段的数目
数据结构·算法·leetcode
疋瓞20 小时前
C++_STL和数据结构《1》_STL、STL_迭代器、c++中的模版、STL_vecto、列表初始化、三个算法、链表
数据结构·c++·算法
JJJJ_iii20 小时前
【左程云算法09】栈的入门题目-最小栈
java·开发语言·数据结构·算法·时间复杂度
Bear on Toilet20 小时前
继承类模板:函数未在模板定义上下文中声明,只能通过实例化上下文中参数相关的查找找到
开发语言·javascript·c++·算法·继承
金融小师妹20 小时前
多因子AI回归揭示通胀-就业背离,黄金价格稳态区间的时序建模
大数据·人工智能·算法
程序员东岸20 小时前
C语言入门指南:字符函数和字符串函数
c语言·笔记·学习·程序人生·算法
小猪咪piggy21 小时前
【算法】day2 双指针+滑动窗口
数据结构·算法·leetcode
max50060021 小时前
OpenSTL PredRNNv2 模型复现与自定义数据集训练
开发语言·人工智能·python·深度学习·算法
budingxiaomoli21 小时前
AVL树知识总结
数据结构·算法