C++ -> DFS 【1】
#include <list>
#include <stack>
#include <vector>
#include <iostream>
using namespace std;
class Graph {
int V;
list<int> *adj;
public:
explicit Graph(int V);
void addEdge(int v, int w);
void DFS(int s);
};
void Graph::addEdge(int v, int w) {
adj[v].push_back(w);
}
Graph::Graph(int V) {
this->V = V;
adj = new list<int>[V];
}
void Graph::DFS(int s) {
// init not visited vector
vector<bool> visited(V, false);
// create stack
stack<int> stack;
stack.push(s);
while (!stack.empty()) {
int s = stack.top(); // 官方提示,top是不返回值的
stack.pop();
if (!visited[s]) {
cout << s << " ";
visited[s] = true;
}
for (auto i = adj[s].begin(); i != adj[s].end(); ++i)
if (!visited[*i])
stack.push(*i);
}
}
int main()
{
Graph g(5); // Total 5 vertices in graph
g.addEdge(1, 0);
g.addEdge(0, 2);
g.addEdge(2, 1);
g.addEdge(0, 3);
g.addEdge(1, 4);
cout << "Following is Depth First Traversal\n";
g.DFS(0);
return 0;
}
//Following is Depth First Traversal
//0 3 2 1 4
//#include <iostream>
//using namespace std;
//
//
多态的原理实现,正常函数是不占用空间的,但是类中若存在虚函数,则会增加一个函数数组指针4个字节,用于指向虚函数表(虚函数函数数组)
//
//
//class Base
//{
//public:
// virtual void f()
// {
// cout << "厉害了 - f!" << endl;
// }
//
// virtual void h()
// {
// cout << "厉害了 - h!" << endl;
// }
// void g()
// {
// cout << "厉害了 - g!" << endl;
// }
//
//private:
// int a;
//
//};
//
//
//
//int main() {
// Base b;
//
// cout << sizeof(b) << endl; // 如果类中没有虚函数,则4个字节,如果有一个或者多个,+12个字节,这是虚函数数组指针
//
// return 0;
//}