BFS 广度优先遍历算法
Lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence, and iteration in both directions.
Compared to other base standard sequence containers (array, vector and deque), lists perform generally better in inserting, extracting and moving elements in any position within the container for which an iterator has already been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.
list对于插入与删除有较高的效率,且自定义sort函数。
#include <list>
#include <vector>
class Graph
{
int V; //顶点数目
list<int> *adj; //指向存储顶点的空间
public:
Graph(int V);
void addEdge(int v, int w);
void BFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); //将顶点w加入顶点v的list中
}
void Graph::BFS(int s)
{
vector<bool> visited(V,false);
list<int> queue;
visited[s] = true;
queue.push_back(s);
list<int>::iterator i;
while(!queue.empty())
{
s = queue.front();
cout << s << " ";
queue.pop_front();
for(i = adj[s].begin(); i != adj[s].end(); ++i)
{
if(!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
DFS 深度优先遍历算法
#include <list>
#include <vector>
class Graph {
int n;
list<int> *adj;
void DFSUtil(int v, vector<bool> &visited);
public:
Graph(int n);
void addEdge(int v, int w);
void DFS(int v);
};
Graph::Graph(int n)
{
this->n = n;
adj = new list<int>[n];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
}
void Graph::DFSUtil(int v, vector<bool> &visited)
{
visited[v] = true;
cout << v << ' ';
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); i++)
{
if (!visited[*i])
{
DFSUtil(*i, visited);
}
}
}
void Graph::DFS(int v)
{
vector<bool> visited(n,false);
for (int i = 0; i < n; i++)
{
if (visited[i] == false)
{
DFSUtil(v, visited);
}
}
}