qq_池鱼_4
2019-03-18 21:45
CMap:
void CMap::BreadthFirstTraverse(int nodeIndex)
{
cout<<m_pNodeArray[nodeIndex].m_cData << " ";
m_pNodeArray[nodeIndex].m_bIsVisited = true;
vector<int> curVec;
curVec.push_back(nodeIndex);
BreadthFirstTraverseImpl(curVec);
}
void CMap::BreadthFirstTraverseImpl(vector<int> preVec)
{
int value = 0;
vector<int> curVec;
for (int j = 0; j < (int)preVec.size(); j++)
{
for (int i = 0; i < m_iCapacity; i++)
{
GetValueFromMatrix(preVec[j], i, value);
if (value != 0)
{
if (m_pNodeArray[i].m_bIsVisited)
{
continue;
}
else
{
cout << m_pNodeArray[i].m_cData <<" ";
m_pNodeArray[i].m_bIsVisited = true;
curVec.push_back(i);
}
}
}
if (curVec.size() == 0)
{
return;
}
else
{
BreadthFirstTraverseImpl(curVec);
}
}
}
bool CMap::GetValueFromMatrix(int row, int col, int &val)
{
if (row < 0 || row >= m_iCapacity)
{
return false;
}
if (col < 0 || col >= m_iCapacity)
{
return false;
}
val = m_pMatrix[row*m_iCapacity+col];
return true;
}
Main:
#include <iostream>
#include <stdlib.h>
#include "CMap.h"
using namespace std;
/*
1
2 3
4 5 6 7
8
1 2 3 4 5 6 7 8
1 1 1
2 1 1 1
3 1 1 1
4 1 1
5 1 1
6 1 1
7 1 1
8 1 1
*/
int main()
{
CMap *map = new CMap(8);
MapNode node1;
node1.m_cData = '1';
MapNode node2;
node2.m_cData = '2';
MapNode node3;
node3.m_cData = '3';
MapNode node4;
node4.m_cData = '4';
MapNode node5;
node5.m_cData = '5';
MapNode node6;
node6.m_cData = '6';
MapNode node7;
node7.m_cData = '7';
MapNode node8;
node8.m_cData = '8';
map->AddNode(&node1);
map->AddNode(&node2);
map->AddNode(&node3);
map->AddNode(&node4);
map->AddNode(&node5);
map->AddNode(&node6);
map->AddNode(&node7);
map->AddNode(&node8);
map->SetValueToMatrixForUndirectedGraph(0, 1);
map->SetValueToMatrixForUndirectedGraph(0, 2);
map->SetValueToMatrixForUndirectedGraph(1, 3);
map->SetValueToMatrixForUndirectedGraph(1, 4);
map->SetValueToMatrixForUndirectedGraph(2, 5);
map->SetValueToMatrixForUndirectedGraph(2, 6);
map->SetValueToMatrixForUndirectedGraph(3, 7);
map->SetValueToMatrixForUndirectedGraph(4, 7);
map->SetValueToMatrixForUndirectedGraph(5, 6);
map->PrintMatrix();
cout << endl;
map->BreadthFirstTraverse(0);
delete map;
map = NULL;
system("pause");
return 0;
}
这个图
我用了自己的类定义、成员函数同时用了你的主程序,得到的结果如下。你的类定义以及成员函数的书写是不是和james的一模一样?老师的代码是有一点问题的,他漏了一个continue,在breadthFirstTraverseImpl函数里面,两个for循环当中,"if(value==0)continue;"他忘了写,对照深度遍历的函数相信你很容易理解。
数据结构探险之图篇
56337 学习 · 81 问题
相似问题
回答 1
回答 1