c++广度优先搜索

c++广度优先搜索_第1张图片
比如,在上面这个简单的有向图上面实现从某个节点开始的广度优先搜索。完整代码在最下方第5小节。

1. 首先建图

struct SimpleGraph {
	std::unordered_map<char, std::vector<char>> edges;

	std::vector<char> neighbors(char id) {
		return edges[id];
	}
};

SimpleGraph example_graph{ {
	{'A',{'B'}},
	{'B',{'C'}},
	{'C',{'B','D','F'}},
	{'D',{'C','E'}},
	{'E',{'F'}},
	{'F',{}},
} };

2. 广度优先搜索

void breadth_first_search(SimpleGraph graph, char start) {
	std::queue<char> frontier;
	frontier.push(start);

	std::unordered_set<char> reached;
	reached.insert(start);

	while (!frontier.empty()) {
		char current = frontier.front();
		frontier.pop();

		std::cout << "visiting " << current << std::endl;
		for (char next : graph.neighbors(current)) {
			if (reached.find(next) == reached.end()) {
				// 说明该点没有被访问过
				 
				// 则加入队列,以后要访问它的邻居
				frontier.push(next);
				// 该点已被访问
				reached.insert(next);
			}
		}
	}
}

3. 测试

std::cout << "reachable from A: " << std::endl;
breadth_first_search(example_graph, 'A');
std::cout << "reachable from E: " << std::endl;
breadth_first_search(example_graph, 'E');

4. 结果

c++广度优先搜索_第2张图片

5. 完整代码

#include
#include
#include
#include
#include

struct SimpleGraph {
	std::unordered_map<char, std::vector<char>> edges;

	std::vector<char> neighbors(char id) {
		return edges[id];
	}
};

SimpleGraph example_graph{ {
	{'A',{'B'}},
	{'B',{'C'}},
	{'C',{'B','D','F'}},
	{'D',{'C','E'}},
	{'E',{'F'}},
	{'F',{}},
} };

void breadth_first_search(SimpleGraph graph, char start) {
	std::queue<char> frontier;
	frontier.push(start);

	std::unordered_set<char> reached;
	reached.insert(start);

	while (!frontier.empty()) {
		char current = frontier.front();
		frontier.pop();

		std::cout << "visiting " << current << std::endl;
		for (char next : graph.neighbors(current)) {
			if (reached.find(next) == reached.end()) {
				// 说明该点没有被访问过
				 
				// 则加入队列,以后要访问它的邻居
				frontier.push(next);
				// 该点已被访问
				reached.insert(next);
			}
		}
	}
}

int main()
{
	std::cout << "reachable from A: " << std::endl;
	breadth_first_search(example_graph, 'A');
	std::cout << "reachable from E: " << std::endl;
	breadth_first_search(example_graph, 'E');

	return 0;
}

你可能感兴趣的:(c++数据结构,算法,c++,宽度优先,算法)