Qt应用:使用深度优先搜索将有向图的根标记为红色。另外有一事不明。
采用邻接矩阵存储。设计一个算法判断有向图是否存在根?
如果存在,将图的顶点标记为红色。
**分析:**题目其实不难。主要分为两部分,一是求根算法,二是界面展示。
因此,我设计的输入是顶点数和邻接矩阵。
输出是在界面上生成图,将根标记为红色。
一、求根算法
求根其实很简单,就是对每个顶点使用搜索算法,我这里选择的是递归形式的深度优先搜索算法。
void dfs(GraphVertex vertex, int & n) {
for (int i = 0; i < _iVertex; i++) {
if (_qVertex[vertex.getID()][i] == 1 && _vecBook[i] == false) {
n++;
_vecBook[i] = true;
dfs(_vecGraphVertex[i], n);
}
}
}
每次记录能够到达的顶点数,搜索完毕之后和顶点数比较就知道这个顶点是不是根了。
二、Qt界面
界面设计如下:
和大多数做法不一样,没有选择输入邻接表的做法
参考Qt使用深度优先搜索和广度优先搜索遍历图_wb175208的博客-CSDN博客的博客,原文是在代码中写死了顶点数和无向图的边;
我给改为从界面上输入顶点数和邻接矩阵,再生成图。这里的难点在于不定长数组的使用。
根据输入的顶点数:
- 在界面上画n*n个输入框,用来输入邻接矩阵的值。
- 初始化对应长度的“顶点”数组,用来在界面上画图。
- 初始化一个二重数组,用来存输入的邻接矩阵的值。
不定长数组使用方式:画n*n个输入框,然后再用布局给排列下。
.h:
QLineEdit*** _lineEdit;
.cpp:
_lineEdit = new QLineEdit**[_iVertex]; // _iVertex是顶点数
for (int i = 0; i < _iVertex; i++)
_lineEdit[i] = new QLineEdit*[_iVertex];
for (int i = 0; i < _iVertex; i++) {
for (int j = 0; j < _iVertex; j++) {
_lineEdit[i][j] = new QLineEdit(this);
}
}
这里有一个问题不明白,我使用了三个指针分别存邻接矩阵、顶点的图形和标记数组。初始化如下
.h:
int **_qVertex;
bool *_vecBook;
GraphVertex *_vecGraphVertex;
.cpp:
_qVertex = new int* [_iVertex];
for (int i = 0; i < _iVertex; i++)
_qVertex[i] = new int[_iVertex];
for (int i = 0; i < _iVertex; i++) {
for (int j = 0; j < _iVertex; j++) {
_qVertex[i][j] = 0;
}
}
_vecBook = new bool[_iVertex];
for (int i = 0; i < _iVertex; i++) {
_vecBook[i] = false;
}
_vecGraphVertex = new GraphVertex[_iVertex];
for (int i = 0; i < _iVertex; i++) {
_vecGraphVertex[i].setID(i);
}
在析构的时候:只有_vecGraphVertex必须要写成:delete[] _vecGraphVertex; 否则就报错?
if (_qVertex != nullptr)
{
delete _qVertex;
_qVertex = nullptr;
}
if (_vecBook != nullptr)
{
delete _vecBook;
_vecBook = nullptr;
}
if (_vecGraphVertex != nullptr)
{
delete[] _vecGraphVertex;
_vecGraphVertex = nullptr;
}
希望有大佬看到解答。
另外,重置的时候要清空QWidget上的布局和控件:
if (ui->wgtMatrix->layout() != NULL)
{
QLayoutItem* item;
while ((item = ui->wgtMatrix->layout()->takeAt(0)) != NULL)
{
delete item->widget();
delete item;
}
delete ui->wgtMatrix->layout();
}
三、结果
最终结果如下:
GIF: