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

在这里插入图片描述
在这里插入图片描述

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

宽度优先搜索(bfs)

#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)

//数字全排序
#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;
}

在这里插入图片描述

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aitee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值