DFS
用于遍历图或树的算法。从起始节点开始,沿着一条路径尽可能深的走下去,直到碰到尽头回溯到上一个节点。
可以使用递归或循环实现。在使用栈来实现时,将节点压入栈中,每次从栈顶取出节点访问子节点,再将其他邻接节点压入栈中。
Stack - First in First out
#include<bits/stdc++.h>
using namespace std;
typedef unordered_map<string, vector<string>> Graph;
Graph graph = {
{"A", {"B", "C"}},
{"B", {"A", "C", "D"}},
{"C", {"A", "B", "D", "E"}},
{"D", {"B", "C", "E", "F"}},
{"E", {"C", "D"}},
{"F", {"D"}}
};;
void dfs(Graph& g, const string& s) {
stack<string> st;
unordered_set<string> seen;
st.push(s);
seen.insert(s);
while(!st.empty()) {
string key = st.top();
st.pop();
vector<string> nodes = graph[key];
for(const string s : nodes) {
if(seen.find(s) == seen.end()) {
st.push(s);
seen.insert(s);
}
}
}
}
int main() {
bfs(graph, "A");
return 0;
}
BFS
Queue - First in Last out