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


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

文章目录

宽度优先搜索(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;
}
相关推荐
এ᭄画画的北北2 小时前
力扣-283.移动零
算法·leetcode
2501_924879365 小时前
口罩识别场景误报率↓79%:陌讯多模态融合算法实战解析
人工智能·深度学习·算法·目标检测·智慧城市
Christo35 小时前
TFS-2022《A Novel Data-Driven Approach to Autonomous Fuzzy Clustering》
人工智能·算法·机器学习·支持向量机·tfs
木木子99995 小时前
超平面(Hyperplane)是什么?
算法·机器学习·支持向量机·超平面·hyperplane
星空下的曙光7 小时前
React 虚拟 DOM Diff 算法详解,Vue、Snabbdom 与 React 算法对比
vue.js·算法·react.js
♞沉寂7 小时前
数据结构——双向链表
数据结构·算法·链表
大阳1237 小时前
数据结构2.(双向链表,循环链表及内核链表)
c语言·开发语言·数据结构·学习·算法·链表·嵌入式
CUC-MenG8 小时前
2025牛客多校第六场 D.漂亮矩阵 K.最大gcd C.栈 L.最小括号串 个人题解
c语言·c++·算法·矩阵
2401_876221348 小时前
Tasks and Deadlines(Sorting and Searching)
c++·算法
我要学习别拦我~9 小时前
逻辑回归建模核心知识点梳理:原理、假设、评估指标与实战建议
算法·机器学习·逻辑回归