-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path7.cpp
111 lines (92 loc) · 2.25 KB
/
7.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
class Graph {
int V; // 顶点的数量
struct Node {
int dest;
struct Node* next;
};
struct Node** adj; // 邻接表
public:
Graph(int V); // 构造函数
void addEdge(int v, int w); // 添加边
void DFS(int v); // 深度优先搜索
void BFS(int v); // 广度优先搜索
};
Graph::Graph(int V) {
this->V = V;
adj = new Node*[V];
for (int i = 0; i < V; i++)
adj[i] = NULL;
}
void Graph::addEdge(int v, int w) {
Node* newNode = new Node;
newNode->dest = w;
newNode->next = adj[v];
adj[v] = newNode;
newNode = new Node;
newNode->dest = v;
newNode->next = adj[w];
adj[w] = newNode;
}
void Graph::DFS(int v) {
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
stack<int> stack;
visited[v] = true;
stack.push(v);
while (!stack.empty()) {
v = stack.top();
cout << v << " ";
stack.pop();
Node* temp = adj[v];
while (temp) {
int adjV = temp->dest;
if (!visited[adjV]) {
stack.push(adjV);
visited[adjV] = true;
}
temp = temp->next;
}
}
}
void Graph::BFS(int v) {
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
queue<int> queue;
visited[v] = true;
queue.push(v);
while (!queue.empty()) {
v = queue.front();
cout << v << " ";
queue.pop();
Node* temp = adj[v];
while (temp) {
int adjV = temp->dest;
if (!visited[adjV]) {
queue.push(adjV);
visited[adjV] = true;
}
temp = temp->next;
}
}
}
int main() {
Graph g(4); // 创建一个有4个顶点的图
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "深度优先搜索结果:";
g.DFS(2);
cout<<endl;
cout << "广度优先搜索结果:";
g.BFS(2);
return 0;
}