2016/11/17 1001. 图的广度优先搜索

本文介绍了一种基于广度优先搜索(BFS)的算法实现,通过使用C++编程语言,展示了如何针对一个给定的图进行遍历。该算法采用列表来辅助实现队列的功能,对每个节点进行访问标记并按顺序访问其所有未访问过的邻居节点。

这个比较简单,只需要按行访问未访问的元素即可(用一个数组记录是否访问的情况),同时访问后将其入队,实现广度优先。队空时遍历完成。

#include <iostream>
#include <list>
#include <string>
using namespace std;
int main()
{
	int n, m;
	cin >> n >> m;
	bool edge[100][100] = { false };
	bool visited[100]= { false };
	string ans = "";
	list <int> BFS;
	for (int i = 0; i <= n - 1; i++)
	{
		for (int j = 0; j <= n - 1; j++)
		{
			cin >> edge[i][j];
		}
	}
	int p = m - 1;
	cout << m << " ";
	visited[p] = true;
	for (;;)
	{
		for (int i = 0; i <= n - 1; i++)
		{
			if (edge[p][i]&&!visited[i])
			{
				ans = ans + (char)(i + 1 + 48) + " ";
				//push
				BFS.push_back(i);
				visited[i] = true;
			}
		}
		if (!BFS.empty())
		{
			p = BFS.front();
			BFS.pop_front();
		}
		else break;
	}
	for (int i = 0; i <= ans.length() - 2; i++)
	{
		cout << ans[i];
	}
	
}


广度优先搜索(BFS)中,`q.push((i, j))` 出现 `no matching member function for call to 'push'` 错误,通常是因为队列 `q` 不支持传入你所提供的参数类型。 ### 错误原因分析 - **队列类型不匹配**:如果 `q` 是一个标准库的 `std::queue`,并且你想要存储坐标 `(i, j)`,那么需要确保队列的元素类型能够正确容纳这两个值。例如,若直接使用 `std::queue<int>`,它只能存储单个整数,不能存储坐标对,此时调用 `push` 传入坐标对就会报错。 - **语法错误**:在 C++ 中,`(i, j)` 是逗号表达式,它的值是 `j`,这可能不是你想要的。你可能想存储一个包含 `i` 和 `j` 的数据结构,如 `std::pair` 或自定义的结构体。 ### 解决办法 #### 使用 `std::pair` ```cpp #include <iostream> #include <queue> #include <utility> int main() { std::queue<std::pair<int, int>> q; int i = 1, j = 2; q.push(std::make_pair(i, j)); // 或者 q.push({i, j}); return 0; } ``` #### 使用自定义结构体 ```cpp #include <iostream> #include <queue> struct Coordinate { int x; int y; Coordinate(int _x, int _y) : x(_x), y(_y) {} }; int main() { std::queue<Coordinate> q; int i = 1, j = 2; q.push(Coordinate(i, j)); return 0; } ``` ### 代码解释 - **使用 `std::pair`**:`std::pair` 是一个标准库提供的模板类,用于存储两个不同类型的值。在 BFS 中,你可以用它来存储坐标对。使用 `std::make_pair` 或花括号初始化语法 `{i, j}` 来创建一个 `std::pair` 对象,然后将其压入队列。 - **使用自定义结构体**:自定义一个结构体 `Coordinate`,包含两个成员变量 `x` 和 `y` 来表示坐标。在构造函数中初始化这两个成员变量。创建 `Coordinate` 对象并将其压入队列。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值