广度优先搜索和深度优先搜索是两种常见的图搜索算法。
广度优先搜索(BFS):从起点开始,按照距离逐层向外搜索,直到找到目标节点或搜索完所有节点。BFS一般使用队列来实现。
深度优先搜索(DFS):从起点开始,沿着一条路径一直搜索到底,直到找到目标节点或者无法继续搜索为止。DFS一般使用递归或栈来实现。
下面是使用C++实现BFS和DFS的示例代码:
BFS实现:
```c++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
vector<int> BFS(vector<vector<int>>& graph, int start) {
vector<int> res;
queue<int> q;
vector<bool> visited(graph.size(), false);
q.push(start);
visited[start] = true;
while (!q.empty()) {
int cur = q.front();
q.pop();
res.push_back(cur);
for (int i : graph[cur]) {
if (!visited[i]) {
q.push(i);
visited[i] = true;
}
}
}
return res;
}
int main() {
vector<vector<int>> graph = {{1, 2}, {0, 2, 3}, {0, 1, 4}, {1, 4}, {2, 3}};
vector<int> res = BFS(graph, 0);
for (int i : res) {
cout << i << " ";
}
cout << endl;
return 0;
}
```
DFS实现:
```c++
#include <iostream>
#include <vector>
using namespace std;
void DFS(vector<vector<int>>& graph, int cur, vector<bool>& visited, vector<int>& res) {
visited[cur] = true;
res.push_back(cur);
for (int i : graph[cur]) {
if (!visited[i]) {
DFS(graph, i, visited, res);
}
}
}
vector<int> DFS(vector<vector<int>>& graph, int start) {
vector<int> res;
vector<bool> visited(graph.size(), false);
DFS(graph, start, visited, res);
return res;
}
int main() {
vector<vector<int>> graph = {{1, 2}, {0, 2, 3}, {0, 1, 4}, {1, 4}, {2, 3}};
vector<int> res = DFS(graph, 0);
for (int i : res) {
cout << i << " ";
}
cout << endl;
return 0;
}
```