0
点赞
收藏
分享

微信扫一扫

图综合练习--拓扑排序

waaagh 2022-01-13 阅读 42
数据结构
#include <bits/stdc++.h>
using namespace std;
const int maxx = 200;
class Graph 
{
public:
    int isFinished[maxx];
    int adjMat[maxx][maxx];
    int n;

public:
    void readAdjMatrix()
    {
        cin >> n;
        for (int i = 0; i < n; i++)
            isFinished[i] = false;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                cin >> adjMat[i][j];
            }
        }
    }
    bool isZeroInDegree(int vertexNo)
    {
        int i;
        for (i = 0; i < n && !adjMat[i][vertexNo]; i++)
        {
            if (i == n - 1 && !adjMat[i][vertexNo])
                return true;
        }
        return false;
    }
    int select()
    {
        for (int i = 0; i < n; i++)
        {
            if (!isFinished[i] && isZeroInDegree(i))
            {
                isFinished[i] = true;
                return i;
            }
        }
        return -1;
    }
    void update(int rootNo)
    {
        for (int j = 0; j < n; j++)
        {
            adjMat[rootNo][j] = 0;
        }
    }
    void topologySort()
    {
        for (int i = 0; i < n; i++)
        {
            int root = select();
            if (root == -1)
                break;

            update(root);
            cout << root << " ";
        }
    }

    void graphMain()
    {
        readAdjMatrix();
        topologySort();
        cout << endl;
    }
};
int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        Graph g;
        g.graphMain();
    }
    return 0;
}
举报

相关推荐

0 条评论