2021-1 图处理算法search的API 深搜/广搜的实现

图搜索的API

起点(source)简单记为s。
如图marked()给出图中v和s有没有相连关系。
search

深度优先搜索

#pragma once

#include"Graph.h"


class depthFirstSearch
{
    
    
public:
	depthFirstSearch(Graph& G, int s);
	
	int count() {
    
     return m_count; }
	bool marked(int v) {
    
     return m_marked->at(v); }

private:
	vector<bool>* m_marked;//标记是否相连
	int m_count;//与source起点连通的顶点数,包括自己

	void dfs(Graph& G, int now);
};


depthFirstSearch::depthFirstSearch(Graph& G, int s)
{
    
    
	m_marked = new vector<bool>(G.V(), false);
	m_count = 0;
	dfs(G, s);
}

inline 
void depthFirstSearch::dfs(Graph& G, int now)
{
    
    
	m_marked->at(now) = true;
	m_count++;

	for (const auto &next : G.adj(now)) {
    
    
		if (!(*m_marked)[next]) {
    
    
			dfs(G, next);
		}
	}
}


广搜

#pragma once
#include<queue>
#include"Graph.h"

class breadthFirstSearch {
    
    
public:
	breadthFirstSearch(Graph& G, int s);

	int count() {
    
     return m_count; }
	bool marked(int v) {
    
     return (*m_marked)[v]; }

private:
	vector<bool>* m_marked=nullptr;
	int m_count = 0;//相连通的节点,不包括自己
	void bfs(Graph& G, int now);
};


breadthFirstSearch::breadthFirstSearch(Graph& G, int s)
{
    
    
	m_marked = new vector<bool>(G.V(), false);
	m_count = 0;
	bfs(G, s);
}
inline void breadthFirstSearch::bfs(Graph& G, int now)
{
    
    
	queue<int> Q;
	(*m_marked)[now] = true;
	Q.push(now);
	while (!Q.empty()) {
    
    

		int v = Q.front();Q.pop();//从队列中删除下一顶点

		for (auto& w : G.adj(v)) {
    
    
			if (!(*m_marked)[w]) {
    
    //邻接点未被标记
				m_marked->at(w) = true;//标记它,并入队
				++m_count;//这里是可变的,其他部分算固定框架
				Q.push(w);
			}
		}
	}

}

关于测试

图的头文件和数据文件在这里:从文件读取构建图https://blog.csdn.net/qq_34890856/article/details/112938237

#include"depthFirstSearch.h"
//#include"breadthFirstSearch.h"

#define out(x) cout<<x<<" "
#define hh printf_s("\n")

void testDFS() {
    
    
	Graph G("data.txt");
	depthFirstSearch dfsG(G, 9);

	bool isconnected = dfsG.marked(0);
	int n = dfsG.count();

	out("9 0 connected ? "), out(isconnected), hh;
	out("how many connect to 9 ? "), out(n), hh;
	//out(G.toString());
}

int main() {
    
    
	testDFS();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34890856/article/details/112949278