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


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

文章目录

宽度优先搜索(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;
}
相关推荐
2301_764441336 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI6 小时前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
Billlly7 小时前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives7 小时前
atcoder ABC 452 题解
数据结构·算法
feifeigo1237 小时前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
fengfuyao9858 小时前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法
无敌昊哥战神9 小时前
深入理解 C 语言:巧妙利用“0地址”手写 offsetof 宏与内存对齐机制
c语言·数据结构·算法
小白菜又菜9 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
Proxy_ZZ09 小时前
用Matlab绘制BER曲线对比SPA与Min-Sum性能
人工智能·算法·机器学习
黎阳之光9 小时前
黎阳之光:以视频孪生领跑全球,赋能数字孪生水利智能监测新征程
大数据·人工智能·算法·安全·数字孪生