int PreVisit(BiTree T) { if (T == NULL) return ERROR; printf("%c ", (T)->data); PreVisit((T)->lchild); PreVisit((T)->rchild); return OK; }
void DFS(Graph* G, int v) { // Depth first search PreVisit(G, v); // Take appropriate action G->setMark(v, VISITED); for (int w=G->first(v); w<G->n(); w = G->next(v,w)) if (G->getMark(w) == UNVISITED) DFS(G, w); PostVisit(G, v); // Take appropriate action }
void BFS(Graph* G, int start, Queue<int>* Q) { int v, w; Q->enqueue(start); // Initialize Q G->setMark(start, VISITED); while (Q->length() != 0) { // Process all vertices on Q v = Q->dequeue(); PreVisit(G, v); // Take appropriate action for (w=G->first(v); w<G->n(); w = G->next(v,w)) if (G->getMark(w) == UNVISITED) { G->setMark(w, VISITED); Q->enqueue(w); } } }
void DFS(Graph* G, int v) { // Depth first search PreVisit(G, v); // Take appropriate action G->setMark(v, VISITED); cout << "\tvisited " << v; cout << "\tw = G->first(" << v << "): " << G->first(v) << endl; for (int w=G->first(v); w<G->n(); w = G->next(v,w)) { if (G->getMark(w) == UNVISITED) { cout << "\t" << w << " unvisited calling DFS(G, " << w << ") " << endl; DFS(G, w); } if (G->next(v,w) == INFINITY_VAL) cout << "\t" << "Return v's next neighbor after w, G->next(v,w), i.e. w = G->next( " << v << ", " << w << ") : " << endl; else cout << "\t" << "Return v's next neighbor after w, G->next(v,w), i.e. w = G->next( " << v << ", " << w << ") : " << G->next(v,w) << endl; } PostVisit(G, v); // Take appropriate action }