06.08.2013 Views

Laboratory Exercises, C++ Programming

Laboratory Exercises, C++ Programming

Laboratory Exercises, C++ Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

22 Tools for Practical <strong>C++</strong> Development<br />

The algorithm should detect cycles in the graph. If that happens, your function should throw<br />

a cyclic exception. The cycle detection is not described in the algorithm; you must add that<br />

yourself.<br />

Topological-Sort(Graph G) {<br />

/* 1. initialize the graph and the result stack */<br />

for each vertex v in G<br />

v.color = WHITE;<br />

Stack result;<br />

/* 2. search from all unvisited vertices */<br />

for each vertex v in G<br />

if (v.color == WHITE)<br />

DFS-visit(v, result);<br />

}<br />

DFS-visit(Vertex v, Stack result) {<br />

/* 1. white vertex v is just discovered, color it gray */<br />

v.color = GRAY;<br />

/* 2. recursively visit all unvisited adjacent nodes */<br />

for each vertex w in v.adj<br />

if (w.color == WHITE)<br />

DFS-visit(w);<br />

/* 3. finish vertex v (color it black and output it) */<br />

v.color = BLACK;<br />

result.push(v.name);<br />

}<br />

A8. Implement top sort and dfs visit and test the program.<br />

4.4 Parsing the Makefile<br />

A9. Finally, you are ready to solve the last part of the assignment: to read a makefile, build a<br />

graph, sort it topologically and print the results. The input to the program is a makefile<br />

containing lines of the type:<br />

target: prereq1 prereq2 ...<br />

The names of the target and the prerequisites are strings. The list of prerequisites may<br />

be empty. The program should perform reasonable syntax checks (the most important is<br />

probably that a line must contain a target).<br />

The file topsort.cc contains a test program. Implement the function buildGraph and<br />

test. The files test[1-5].txt contain test cases (the same that were used in the graph test<br />

program in assignment A8), but you are encouraged to also test other cases.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!