基于深搜
#include <vector>
#include <iostream>
using namespace std;
#define MAX 7
char node[MAX];
int node_edge[MAX][MAX];
vector<char> dfs;
bool visited[MAX];
void InPut()
{
cout << "Input nodes :" << endl;
for (int i = 0; i < MAX; i++)
{
cin >> node[i];
}
cout << "Input edges:" << endl;
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
{
cin >> node_edge[i][j];
}
}
memset(visited, false, MAX);
}
void DFS_sort()
{
int temp[MAX];
memset(temp, 1, MAX * 4);
for (int j = 0; j < MAX; j++)
{
int i = 0;
for (i; i < MAX; i++)
{
if (node_edge[i][j] == 1)
{
break;
}
}
if (i == MAX)
{
temp[j] = 0;
}
}
vector<char> values;
char n = node[0];
if (temp[0] == 0)
{
temp[0] = 1;
}
dfs.push_back(n);
while (!dfs.empty())
{
char ch = dfs.back();
int index;
for (index = 0; index < MAX; index++)
{
if (node[index] == ch)
{
break;
}
}
if (visited[index] == false)
{
int i;
for (i = 0; i < MAX; i++)
{
if (node_edge[index][i] == 1 && visited[i] == false)
{
dfs.push_back(node[i]);
break;
}
}
if (i == MAX)
{
values.push_back(ch);
visited[index] = true;
dfs.pop_back();
if (dfs.empty())
{
for (int i = 0; i < MAX; i++)
{
if (temp[i] == 0)
{
dfs.push_back(node[i]);
temp[i] = 1;
}
}
}
}
continue;
}
}
for (int i = MAX - 1; i >= 0; i--)
{
cout << values.at(i) << " ";
}
}
int main()
{
InPut();
DFS_sort();
return 0;
}
减治法
void Sub_sort()
{
int temp[MAX];
memset(temp, 1, MAX * 4);
for (int j = 0; j < MAX; j++)
{
int in = 0;
for (int i = 0; i < MAX; i++)
{
if (node_edge[i][j] == 1)
{
in++;
}
}
temp[j] = in;
}
vector<char> values;
for (int i = 0; i < MAX; i++)
{
if (temp[i] == 0)
{
dfs.push_back(node[i]);
temp[i] = -1;
}
}
while (!dfs.empty())
{
char ch = dfs.back();
int index;
for (index = 0; index < MAX; index++)
{
if (node[index] == ch)
{
break;
}
}
cout << node[index] << " ";
dfs.pop_back();
for (int j = 0; j < MAX; j++)
{
if (node_edge[index][j] == 1)
{
temp[j]--;
}
}
for (int i = 0; i < MAX; i++)
{
if (temp[i] == 0)
{
dfs.push_back(node[i]);
temp[i] = -1;
}
}
}
}