广度优先遍历
重复2过程,一直将出队列首节点,并将该节点指向未访问的节点入队列,并标记成已访问
void BFS(const V& vertex)
{
queue<int> q;
int curi = findIndex(vertex);
int n = _vertexs.size();
q.push(curi);
vector<bool> visited(n, false);
visited[curi] = true;
while (!q.empty())
{
curi = q.front();
q.pop();
cout<< _vertexs[curi] << " ";
for (int i = 0; i < n; i++)
{
if (_matrix[curi][i] != MAX_W && visited[i] == false)
{
q.push(i);
visited[i] = true;
}
}
}
}
void TestGraphBFS()
{
const char* s = "ABCDEFGHI";
Graph<char, int> g1(s,9);
g1.AddEdge('A', 'B', 2);
g1.AddEdge('A', 'C', 3);
g1.AddEdge('A', 'D', 4);
g1.AddEdge('B', 'E', 5);
g1.AddEdge('C', 'F', 6);
g1.AddEdge('D', 'F', 7);
g1.AddEdge('E', 'G', 8);
g1.AddEdge('F', 'H', 9);
g1.AddEdge('H', 'I', 1);
g1.BFS('A');
}
深度优先遍历
void DFS(const V& vertex)
{
int n = _vertexs.size();
vector<bool> visited(n, false);
int curi = findIndex(vertex);
_DFS(curi, visited);
}
void _DFS(int curi, vector<bool>& visited)
{
cout << _vertexs[curi] << " ";
visited[curi] = true;
int n = _vertexs.size();
for (int i = 0; i < n; ++i)
{
if (_matrix[curi][i] != MAX_W && visited[i] == false)
{
_DFS(i, visited);
}
}
}
void TestGraphDFS()
{
const char* s = "ABCDEFGHI";
Graph<char, int> g1(s,9);
g1.AddEdge('A', 'B', 2);
g1.AddEdge('A', 'C', 3);
g1.AddEdge('A', 'D', 4);
g1.AddEdge('B', 'E', 5);
g1.AddEdge('C', 'F', 6);
g1.AddEdge('D', 'F', 7);
g1.AddEdge('E', 'G', 8);
g1.AddEdge('F', 'H', 9);
g1.AddEdge('H', 'I', 1);
g1.DFS('A');
}