function2(std::vector<std::vector<int> >& vec)//传引用
function3(std::vector<std::vector<int> >* vec)//传指针
解决这道题时P5318 【深基18.例3】查找文献, 在ide里测试时只有运行时错误,但在我自己的编辑器上运行地毫无问题:
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
void DFS(vector<int> graph[], int start, set<int> *visited, vector<int> *ret) {
if ((*visited).count(start)) {
return;
} else {
(*visited).insert(start);
(*ret).push_back(start);
}
for (int i = 0; i < graph[start].size(); i++) {
DFS(graph, graph[start][i], visited, ret);
}
}
void BFS(vector<int> graph[], int start, set<int> *visited, vector<int> *ret) {
vector<int> level;
vector<int> base;
base.push_back(start);
while (base.size() != 0) {
for (int i = 0; i < base.size(); i++) {
if((*visited).count(base[i])){
continue;
}else{
(*visited).insert(base[i]);
(*ret).push_back(base[i]);
}
for (int j = 0; j < graph[base[i]].size(); j++) {
level.push_back(graph[base[i]][j]);
}
}
base = level;
level.clear();
}
}
int main() {
int V, E;
// 此图有size个点,
cin >> V;
cin >> E;
vector<int> graph[V];
int in, out;
cin >> in;
cin >> out;
graph[in].push_back(out);
int start = in;
for (int i = 0; i < E - 1; i++) {
cin >> in;
cin >> out;
graph[in].push_back(out);
}
for (int i = 0; i < V; i++) {
sort(graph[i].begin(), graph[i].end());
}
// 深度优先
set<int> visited;
vector<int> ret;
DFS(graph, start, &visited, &ret);
for (int i = 0; i < ret.size(); i++) {
cout << ret[i] << " ";
}
visited.clear();
ret.clear();
cout << endl;
BFS(graph, start, &visited, &ret);
for (int i = 0; i < ret.size(); i++) {
cout << ret[i] << " ";
}
return 0;
}
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
void DFS(vector<int> graph[], int start, set<int> &visited, vector<int> &ret) {
if (visited.count(start)) {
return;
} else {
visited.insert(start);
ret.push_back(start);
}
for (int i = 0; i < graph[start].size(); i++) {
DFS(graph, graph[start][i], visited, ret);
}
}
void BFS(vector<int> graph[], int start, set<int> &visited, vector<int> &ret) {
vector<int> level;
vector<int> base;
base.push_back(start);
while (base.size() != 0) {
for (int i = 0; i < base.size(); i++) {
if(visited.count(base[i])){
continue;
}else{
visited.insert(base[i]);
ret.push_back(base[i]);
}
for (int j = 0; j < graph[base[i]].size(); j++) {
level.push_back(graph[base[i]][j]);
}
}
base = level;
level.clear();
}
}
int main() {
int V, E;
// 此图有size个点,
cin >> V;
cin >> E;
vector<int> graph[V];
int in, out;
cin >> in;
cin >> out;
graph[in].push_back(out);
int start = in;
for (int i = 0; i < E - 1; i++) {
cin >> in;
cin >> out;
graph[in].push_back(out);
}
for (int i = 0; i < V; i++) {
sort(graph[i].begin(), graph[i].end());
}
// 深度优先
set<int> visited;
vector<int> ret;
DFS(graph, start, visited, ret);
for (int i = 0; i < ret.size(); i++) {
cout << ret[i] << " ";
}
visited.clear();
ret.clear();
cout << endl;
BFS(graph, start, visited, ret);
for (int i = 0; i < ret.size(); i++) {
cout << ret[i] << " ";
}
return 0;
}
请问有大佬能解答下原因吗?应该怎么改