บทนำ
การจัดลำดับโพสตะลิส (Topological Sorting) ของกราฟมีทิศทางไม่มีวงจร (DAG) คือการเรียงลำดับจุดยอด (vertices) แบบเส้นตรง โดยที่สำหรับทุกเส้นเชื่อมทิศทาง uv จุด u จะมาก่อนจุด v ในลำดับนั้น หากกราฟไม่ใช่ DAG การจัดลำดับโพสตะลิสจะทำไม่ได้
ฟังก์ชันและ Pseudocode
Begin
function topologicalSort():
a) ทำเครื่องหมายโหนดปัจจุบันว่าเยี่ยมชมแล้ว
b) เรียกซ้ำ (Recur) สำหรับทุกโหนดที่ติดกับโหนดนี้
c) นำโหนดปัจจุบันเข้า stack ที่เก็บผลลัพธ์
End
Begin
function topoSort() ใช้ topologicalSort() แบบเรียกซ้ำ:
a) ทำเครื่องหมายทุกโหนดว่าไม่ได้เยี่ยมชม
b) เรียกฟังก์ชัน topologicalSort()
c) แสดงผลลัพธ์
End
ตัวอย่างโค้ด C++
#include <iostream>
#include <list>
#include <stack>
using namespace std;
class Graph {
int V;
list<int> *adj;
void topologicalSort(int v, bool visited[], stack<int> &Stack);
public:
Graph(int V);
void addEdge(int v, int w);
void topoSort();
};
Graph::Graph(int V) {
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w) {
adj[v].push_back(w);
}
void Graph::topologicalSort(int v, bool visited[], stack<int> &Stack) {
visited[v] = true;
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
topologicalSort(*i, visited, Stack);
Stack.push(v);
}
void Graph::topoSort() {
stack<int> Stack;
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
for (int i = 0; i < V; i++)
if (visited[i] == false)
topologicalSort(i, visited, Stack);
while (Stack.empty() == false) {
cout << Stack.top() << " ";
Stack.pop();
}
}
int main() {
Graph g(6);
g.addEdge(4, 2);
g.addEdge(5, 1);
g.addEdge(4, 0);
g.addEdge(3, 1);
g.addEdge(1, 3);
g.addEdge(3, 2);
cout << " Topological Sort of the given graph \n";
g.topoSort();
return 0;
}
ผลลัพธ์
Topological Sort of the given graph 5 4 1 3 2 0