1. 程式人生 > 其它 >2021-1 圖處理演算法search的API 深搜/廣搜的實現

2021-1 圖處理演算法search的API 深搜/廣搜的實現

技術標籤:日常練習演算法dfs圖解法c++

圖搜尋的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;
}