voiddfs(int v){for(int i =1; i <= n; i++){//給鏈表排序,保證輸出拓撲序bubbleSortListMax(G[i].head);}stack<int> s;s.push(v);while(!s.empty()){int w = s.top();s.pop();if(visit[w]==0){cout << w <<" ";visit[w]=1;list p = G[w].head;while(p){if(visit[p->vert]==0){s.push(p->vert);}p = p->next;}}}}
廣度優先搜索(bfs)
voidbfs(int v){for(int i =1; i <= n; i++){visit[i]=0;}for(int i =1; i <= n; i++){//給鏈表排序,保證輸出拓撲序bubbleSortListMin(G[i].head);}queue<int> q;cout << v <<" ";visit[v]=1;q.push(v);while(!q.empty()){int w = q.front();q.pop();list p = G[w].head;while(p){if(visit[p->vert]==0){cout << p->vert <<" ";visit[p->vert]=1;q.push(p->vert);}p = p->next;}}}