数据结构与算法之深度优先 工业级实现 STL 容器 / 自定义栈

数据结构与算法阿木 发布于 5 天前 1 次阅读


摘要:

深度优先搜索(Depth-First Search,DFS)是一种常用的图遍历算法,广泛应用于算法竞赛、数据挖掘、路径规划等领域。本文将围绕深度优先搜索的工业级实现,探讨STL容器和自定义栈在DFS中的应用,并给出相应的代码实现。

一、

深度优先搜索是一种非回溯的遍历算法,它从根节点开始,沿着一条路径一直走到头,然后回溯到上一个节点,再寻找新的路径。DFS在图论中有着广泛的应用,如拓扑排序、最小生成树、最短路径等。本文将详细介绍DFS的工业级实现,并探讨STL容器和自定义栈在DFS中的应用。

二、深度优先搜索的基本原理

深度优先搜索的基本思想是:从根节点开始,沿着一条路径一直走到头,然后回溯到上一个节点,再寻找新的路径。在遍历过程中,可以使用一个栈来存储待访问的节点。

三、STL容器在DFS中的应用

C++标准库中的STL容器提供了丰富的数据结构,如vector、list、stack等。在DFS中,可以使用stack容器来实现深度优先搜索。

1. 使用vector实现栈

cpp

include <iostream>


include <vector>

using namespace std;

class Stack {


private:


vector<int> elements;

public:


void push(int value) {


elements.push_back(value);


}

int pop() {


if (elements.empty()) {


throw std::out_of_range("Stack is empty");


}


return elements.back();


}

bool isEmpty() const {


return elements.empty();


}


};

void dfs(int root, vector<bool>& visited, const vector<vector<int>>& graph) {


Stack stack;


stack.push(root);

while (!stack.isEmpty()) {


int node = stack.pop();


if (!visited[node]) {


visited[node] = true;


cout << "Visited: " << node << endl;

// 遍历邻接节点


for (int neighbor : graph[node]) {


if (!visited[neighbor]) {


stack.push(neighbor);


}


}


}


}


}

int main() {


int n = 5; // 节点数量


vector<vector<int>> graph(n);


graph[0] = {1, 2};


graph[1] = {0, 3};


graph[2] = {0, 4};


graph[3] = {1};


graph[4] = {2};

vector<bool> visited(n, false);


dfs(0, visited, graph);

return 0;


}


2. 使用list实现栈

cpp

include <iostream>


include <list>

using namespace std;

class Stack {


private:


list<int> elements;

public:


void push(int value) {


elements.push_front(value);


}

int pop() {


if (elements.empty()) {


throw std::out_of_range("Stack is empty");


}


return elements.front();


}

bool isEmpty() const {


return elements.empty();


}


};

// ... (dfs函数与上面相同)


四、自定义栈在DFS中的应用

除了使用STL容器中的stack,还可以自定义栈来实现DFS。

cpp

include <iostream>


include <vector>

using namespace std;

class Stack {


private:


vector<int> elements;

public:


void push(int value) {


elements.push_back(value);


}

int pop() {


if (elements.empty()) {


throw std::out_of_range("Stack is empty");


}


return elements.back();


}

bool isEmpty() const {


return elements.empty();


}


};

void dfs(int root, vector<bool>& visited, const vector<vector<int>>& graph) {


Stack stack;


stack.push(root);

while (!stack.isEmpty()) {


int node = stack.pop();


if (!visited[node]) {


visited[node] = true;


cout << "Visited: " << node << endl;

// 遍历邻接节点


for (int neighbor : graph[node]) {


if (!visited[neighbor]) {


stack.push(neighbor);


}


}


}


}


}

int main() {


// ... (图和dfs函数与上面相同)


}


五、总结

本文介绍了深度优先搜索的工业级实现,并探讨了STL容器和自定义栈在DFS中的应用。通过使用STL容器或自定义栈,可以方便地实现DFS算法,并应用于各种实际问题。在实际开发中,可以根据具体需求选择合适的数据结构和算法,以提高程序的性能和可维护性。

(注:本文代码示例仅供参考,实际应用中可能需要根据具体情况进行调整。)