Week 07 Lab Exercise

Graph Traversal

Objectives

  • To get some practice with graphs
  • To get some practice with implementing graph traversal
  • To understand the difference between graph traversal methods
  • To get some practice solving problems using graph traversal
  • To get some practice working with different graph representations
  • To get some practice with time complexity analysis

Admin

Marks
5 (see the Assessment section for more details)
How to submit
see the Submission section
Deadline to submit
12pm Monday of Week 8
Submission late penalty
0.2% per hour or part thereof deducted from the attained mark, submissions later than 5 days not accepted
When to get handmarked
in your Week 7, 8 or 9 lab session (after you have submitted)
Note: You must get your work handmarked to receive marks for the lab. If you do not get your work handmarked, you will receive 0 marks for the entire lab exercise, regardless of your automarking result.

Click here to request handmarking

Note that you must be physically present in the lab to get handmarked, and you must be prepared to explain your work. During handmarking, if you take too long to explain your work or recall what you did, you may be moved to the end of the queue.

Background

In lectures, we learned about two graph traversal methods: breadth-first search (BFS) and depth-first search (DFS). BFS visits vertices in order of distance from the source vertex and is useful for finding the shortest path (in an unweighted graph). Meanwhile, DFS goes as far down one path as possible before backtracking, and is useful in applications that require backtracking, such as finding a cycle or a Hamiltonian path. DFS can also be implemented recursively.

This diagram shows the difference in behaviour between BFS and DFS.

Setting Up

Create a directory for this lab, change into it, and run the following command:

unzip /web/cs2521/26T3/labs/week07/downloads/files.zip

If you're working at home, download files.zip by clicking on the above link and then unzip the downloaded file.

If you've done the above correctly, you should now have the following files:

Makefile
a set of dependencies used to control compilation
Graph.h
interface to the Graph ADT
GraphAdjList.c
implementation of the Graph ADT using the adjacency list representation
GraphAdjListRep.h
definition of the adjacency list representation
GraphAdjMatrix.c
implementation of the Graph ADT using the adjacency matrix representation
GraphAdjMatrixRep.h
definition of the adjacency matrix representation
graphReader.h
interface to the graph reader module
graphReader.c
implementation of the graph reader module
Queue.h
interface to the Queue ADT
Queue.c
implementation of the Queue ADT
Stack.h
interface to the Stack ADT
Stack.c
implementation of the Stack ADT
bfsTree.c
main program for implementing and testing bfsTree (Task 1)
dfsTree.c
main program for implementing and testing dfsTree (Task 2)
shortestPath.c
main program for implementing and testing shortestPath (Task 3)
cycle.c
main program for implementing and testing cycle (Task 4)
furthestVertex.c
main program for implementing and testing furthestVertex (Task 5)
largestComponent.c
main program for implementing and testing largestComponent (Task 6)
iterativeDfsTree.c
main program for implementing and testing iterativeDfsTree (optional task)
graphs/
directory containing example graphs for testing
analysis.txt
a template for you to enter your time complexity analysis

Once you've got these files, the first thing to do is to run the command

make

This will compile the initial version of the files and produce several executables for the tasks below.

File Walkthrough

Graph.h

This is the interface to the Graph ADT. Graphs are undirected and unweighted.

GraphAdjList.c and GraphAdjMatrix.c

These are two different implementations of the Graph ADT. GraphAdjList.c uses the adjacency list representation, and GraphAdjMatrix.c uses the adjacency matrix representation. To help you get familiar with using both, some tasks will require you use one, and some tasks will require you to use the other.

GraphAdjListRep.h and GraphAdjMatrixRep.h

These files contain the definitions of the data structures used in the adjacency list and adjacency matrix representations respectively. The data structures would typically be defined in the same file as the ADT implementation (i.e., in the above .c files), but for the purposes of separating the code for each task into different files, we have placed them in separate header files and #include'd them so that you are able to access them directly.

Queue.h and Stack.h

These are the interfaces to the Queue and Stack ADTs respectively.

graphs/

This directory contains graph files for testing. In each graph file, the first line contains one integer which is the number of vertices, and each of the remaining lines contains two integers \(u\) and \(v\) indicating that there is an edge between \(u\) and \(v\). We have created a tool to help you visualise these graphs (see below).

⭐️ Graph Visualiser ⭐️

We have created a graph visualiser tool to help you visualise graphs and verify your program's output.

You can choose to view just one graph in 1-graph mode, or two graphs side by side in 2-graph mode. 2-graph mode is useful for when you need to compare two similar graphs.

To view a graph, click "Import graph...", and enter the graph into the text box in the correct format. There are two accepted formats:

  • Graph file format: This is the format used by the graph files in the graphs/ directory. In this format, the first line contains one integer which is the number of vertices, and each of the remaining lines contains two integers \(u\) and \(v\) indicating that there is an edge between \(u\) and \(v\). For example:
    3
    0 1
    1 2
    
  • GraphShow() format: This is the format outputted by the GraphShow function, which is used by all the main programs. After running a program, you can simply copy and paste the graph output into the text box. For example:
    Number of vertices: 3
    Edges:
     0: 1
     1: 0 2
     2: 1
    

Task 1 - BFS Tree

One idea discussed in lectures is that if we perform a graph traversal and take all the edges were used during the traversal (i.e., edges that led to an unvisited vertex during the traversal), these edges produce a spanning tree.

For example, consider the following graph:

If a breadth-first search was performed on the graph starting from vertex 0, then the edges used during the BFS would produce the following spanning tree:

One way to identify these edges is to use the predecessor array from the graph traversal, since the edges in the spanning tree simply connect each vertex to its predecessor. For example, the predecessor array below was produced from a BFS on the above graph starting from vertex 0. You can check it against the spanning tree shown above.

Index 0 1 2 3 4 5 6 7 8
- 0 0 0 2 1 3 5 6

Your task is to implement breadth-first search and then return the spanning tree produced by the BFS as a graph. Implement this function in bfsTree.c:

Graph bfsTree(Graph g, int src);

This function takes a graph and a vertex src, and returns a new graph which is the spanning tree produced by a BFS in the graph starting from src. The BFS should prioritise lower-numbered vertices, so if a vertex has multiple neighbours, they should be enqueued in increasing order.

You can assume that the graph is connected and contains at least two vertices.

For this task, you must use the adjacency matrix representation, which is defined in GraphAdjMatrixRep.h.

Here is the pseudocode for BFS:

bfs(g, src):
	Inputs: graph g
	        source vertex src
	
	initialise visited and predecessor arrays
	create queue and enqueue src

	mark src as visited
	while the queue is not empty:
		dequeue u

		for each neighbour v of u:
			if v has not been visited:
				mark v as visited
				set predecessor of v to u
				enqueue v
Hint: When creating the new spanning tree graph, you can use GraphInsertEdge to insert edges.

Testing

Once you think you've got the function working, test it by recompiling with make and running the bfsTree program. The program takes two command-line arguments: the path to a graph file, and a source vertex. For example:

make
...
./bfsTree graphs/graph-1.txt 0
-----
Graph
-----
Number of vertices: 9
Edges:
 0: 1 2 3
 1: 0 3 5
 2: 0 3 4
 3: 0 1 2 6
 4: 2
 5: 1 7
 6: 3 7 8
 7: 5 6
 8: 6

----------------------
BFS tree from vertex 0
----------------------
Number of vertices: 9
Edges:
 0: 1 2 3
 1: 0 5
 2: 0 4
 3: 0 6
 4: 2
 5: 1 7
 6: 3 8
 7: 5
 8: 6

You can check whether the output is correct by using the graph visualiser tool. First, switch to 2-graph mode, then copy the input graph into the first panel, and then copy the output graph into the second panel. After moving the vertices around, you should get the following:

Task 2 - DFS Tree

Similarly, graph traversal with depth-first search also produces a spanning tree.

For example, depth-first search on the graph shown in Task 1 would produce the following spanning tree (assuming that the DFS prioritises lower-numbered vertices):

Your task is to implement recursive depth-first search and then return the spanning tree produced by the DFS as a graph. Implement this function in dfsTree.c:

Graph dfsTree(Graph g, int src);

This function takes a graph and a vertex src, and returns a new graph which is the spanning tree produced by a DFS in the graph starting from src. The DFS should prioritise lower-numbered vertices, so if a vertex has multiple neighbours, the neighbour with the lowest number should be visited first.

You can assume that the graph is connected and contains at least two vertices.

For this task, you must use the adjacency list representation, which is defined in GraphAdjListRep.h.

Here is the pseudocode for DFS:

dfs(g, src):
	Inputs: graph g
	        source vertex src
	
	initialise visited and predecessor arrays

	recursiveDfs(g, src, visited, predecessor)

recursiveDfs(g, u, visited, predecessor):
	mark u as visited

	for each neighbour v of u:
		if v has not been visited:
			set predecessor of v to u
			recursiveDfs(g, v, visited, predecessor)

Testing

Once you think you've got the function working, test it by recompiling with make and running the dfsTree program. The program takes two command-line arguments: the path to a graph file, and a source vertex. For example:

make
...
./dfsTree graphs/graph-1.txt 0
-----
Graph
-----
Number of vertices: 9
Edges:
 0: 1 2 3
 1: 0 3 5
 2: 0 3 4
 3: 0 1 2 6
 4: 2
 5: 1 7
 6: 3 7 8
 7: 5 6
 8: 6

----------------------
DFS tree from vertex 0
----------------------
Number of vertices: 9
Edges:
 0: 1
 1: 0 3
 2: 3 4
 3: 1 2 6
 4: 2
 5: 7
 6: 3 7 8
 7: 5 6
 8: 6

As in the previous task, you can check whether the output is correct by using the graph visualiser tool.

Intermission 📻️

The remaining tasks in this lab involve solving graph problems, where you will need to decide which graph traversal method, BFS or DFS, is more suitable, and then use your chosen method to solve the problem. This means you may be able to reuse some of your code from Tasks 1 and 2.

Note that a Queue ADT will be available in each task, but this does not necessarily mean that it is needed in every task. Also note that the Stack ADT will not be available - if you choose to use DFS, you will need to implement it recursively.

Task 3 - Find the Shortest Path

Your task is to implement this function in shortestPath.c:

int shortestPath(Graph g, int src, int dest, int path[]);

This function takes a graph, a source vertex src, a destination vertex dest, and an array path, and finds the shortest path from src to dest. It should store the path as a sequence of vertices in the given path array and return the number of vertices stored in the array. If there is no path from src to dest, the function should return 0. If there are multiple shortest paths from src to dest, it may return any of them.

For example, consider the following graph:

If src is 0 and dest is 10, then the function should store the path [0, 6, 1, 10] in the path array and return 4.

For this task, you must use the adjacency list representation, which is defined in GraphAdjListRep.h.

Testing

Once you think you've got the function working, test it by recompiling with make and running the shortestPath program. The program takes three command-line arguments: the path to a graph file, a source vertex and a destination vertex. For example:

make
...
./shortestPath graphs/graph-2.txt 0 10
-----
Graph
-----
Number of vertices: 11
Edges:
 0: 3 4 6
 1: 5 6 8 10
 2: 9 10
 3: 0 6 7
 4: 0 5
 5: 1 4 6 9
 6: 0 1 3 5
 7: 3
 8: 1
 9: 2 5
 10: 1 2

Shortest path from 0 to 10: 0 6 1 10

Analysis 🔍

When you're certain that the function works correctly, determine its worst-case time complexity and write it in analysis.txt along with an explanation. The time complexity should be in terms of \( V \) and/or \( E \), where \( V \) is the number of vertices in the graph and \( E \) is the number of edges in the graph.

Task 4 - Find a Cycle

Your task is to implement this function in cycle.c:

int cycle(Graph g, int path[]);

This function takes a graph and an array path, and finds a cycle in the graph. It should store the cycle as a sequence of vertices in the given path array such that the first and last vertices are the same (showing that it is a cycle), and return the number of vertices stored in the array. If there is no cycle in the graph, the function should return 0. If there are multiple cycles, it may return any of them.

For example, consider the following graph:

The function should store one of the following sequences in the path array and return 5.

[1, 2, 6, 5, 1]
[1, 5, 6, 2, 1]
[2, 6, 5, 1, 2]
[2, 1, 5, 6, 2]
[6, 5, 1, 2, 6]
[6, 2, 1, 5, 6]
[5, 1, 2, 6, 5]
[5, 6, 2, 1, 5]
For this task, you must use the adjacency matrix representation, which is defined in GraphAdjMatrixRep.h.

Hints

Please give the task at least 10 minutes of thought before looking at these hints!

The problem of checking if a cycle exists is covered in lectures. How can you modify the solution to get the vertices in the cycle?

Think about how you could use a predecessor array to get the vertices in the cycle.

As soon as you detect a cycle during the graph traversal, use the predecessor array to trace backwards through the cycle. Be careful, because the source vertex might not be part of the cycle!

Testing

Once you think you've got the function working, test it by recompiling with make and running the cycle program. The program takes one command-line argument: the path to a graph file. For example:

make
...
./cycle graphs/graph-3.txt
-----
Graph
-----
Number of vertices: 7
Edges:
 0: 1 4
 1: 0 2 5
 2: 1 3 6
 3: 2
 4: 0
 5: 1 6
 6: 2 5

Cycle: 1 5 6 2 1

Analysis 🔍

When you're certain that the function works correctly, determine its worst-case time complexity and write it in analysis.txt along with an explanation. The time complexity should be in terms of \( V \) and/or \( E \), where \( V \) is the number of vertices in the graph and \( E \) is the number of edges in the graph.

Task 5 - Find the Furthest Vertex

Your task is to implement this function in furthestVertex.c:

struct result furthestVertex(Graph g, int src);

This function takes a graph and a source vertex src, and finds the vertex which is furthest from src but still reachable. It should return that vertex and its distance from src in a struct result, which is defined as follows:

struct result {
	int vertex;
	int distance;
};

If there are multiple vertices which are furthest from src, the function may return any of them.

For example, consider the following graph:

If src is 0, then the function should return a struct result with vertex set to 6 and distance set to 5.

For this task, you must use the adjacency matrix representation, which is defined in GraphAdjMatrixRep.h.

Testing

Once you think you've got the function working, test it by recompiling with make and running the furthestVertex program. The program takes two command-line arguments: the path to a graph file and a source vertex. For example:

make
...
./furthestVertex graphs/graph-4.txt 0
-----
Graph
-----
Number of vertices: 12
Edges:
 0: 3 7
 1: 3
 2: 3 5 7 11
 3: 0 1 2
 4: 10 11
 5: 2 9
 6: 8
 7: 0 2 11
 8: 6 9 10
 9: 5 8 11
 10: 4 8
 11: 2 4 7 9

Furthest vertex: 6 (distance = 5)
No time complexity analysis is required for this task.

Task 6 - Find the Largest Component

Your task is to implement this function in largestComponent.c:

int largestComponent(Graph g, int component[]);

This function takes a graph and finds the largest connected component in the graph, which is the connected component that contains the most vertices. It should store the vertices in this component in the given component array (in any order) and return the number of vertices stored. If there are multiple connected components containing the most vertices, the function may return any of them.

For example, consider the following graph:

The largest connected component is the component that contains the vertices 3, 4, 6, 7 and 12, so the function should store these vertices in the component array (in any order) and return 5.

For this task, you must use the adjacency list representation, which is defined in GraphAdjListRep.h.

Testing

Once you think you've got the function working, test it by recompiling with make and running the largestComponent program. The program takes one command-line argument: the path to a graph file. For example:

make
...
./largestComponent graphs/graph-5.txt
-----
Graph
-----
Number of vertices: 14
Edges:
 0: 2 10
 1: 8
 2: 0
 3: 6 12
 4: 6 12
 5: 13
 6: 3 4 7
 7: 6 12
 8: 1 9 11
 9: 8
 10: 0
 11: 8
 12: 3 4 7
 13: 5

Largest component contains 5 vertices: 3 4 6 7 12
No time complexity analysis is required for this task.

Optional Task - Iterative DFS Tree

Note: This task is optional. It is not worth any marks.

Your task is to implement iterative depth-first search and then return the spanning tree produced by the DFS as a graph. Implement this function in iterativeDfsTree.c:

Graph iterativeDfsTree(Graph g, int src);

This function takes a graph and a vertex src, and returns a new graph which is the spanning tree produced by a DFS in the graph starting from src. The DFS should prioritise lower-numbered vertices, so if a vertex has multiple neighbours, the neighbour with the lowest number should be visited first.

You can assume that the graph is connected and contains at least two vertices.

Your solution must use the provided Stack ADT.

Note: Recursion is forbidden in this task.
For this task, you must use the adjacency matrix representation, which is defined in GraphAdjMatrixRep.h.

Testing

Once you think you've got the function working, test it by recompiling with make and running the iterativeDfsTree program. The program takes two command-line arguments: the path to a graph file, and a source vertex. For example:

make
...
./iterativeDfsTree graphs/graph-1.txt 0
-----
Graph
-----
Number of vertices: 9
Edges:
 0: 1 2 3
 1: 0 3 5
 2: 0 3 4
 3: 0 1 2 6
 4: 2
 5: 1 7
 6: 3 7 8
 7: 5 6
 8: 6

----------------------
DFS tree from vertex 0
----------------------
Number of vertices: 9
Edges:
 0: 1
 1: 0 3
 2: 3 4
 3: 1 2 6
 4: 2
 5: 7
 6: 3 7 8
 7: 5 6
 8: 6

Submission

Submit via the command line using the give command:

give cs2521 lab07

You can also submit via give's web interface. You can submit multiple times. Only your last submission will be marked. You can check the files you have submitted here.

Assessment

Mark Breakdown

Aspect Marks Description
Code correctness 4 Your code for each task will be automarked. Automarking will be run after submissions have closed. After automarking is run you will be able to view your results here.
Complexity analysis 1 Your tutor will check that you have completed the time complexity analysis for each of the required functions in analysis.txt and ask you to re-explain your analysis for each function. Analysis of each function is worth 0.5 marks.

Note that you should be prepared to explain your analysis without reading from analysis.txt, but your written explanation should still be thorough. We have provided some advice for writing a thorough time complexity analysis below.

Complexity Analysis Guidelines

Your time complexity analysis should be thorough and cover all parts of a function (except possibly simple \(O(1)\) edge cases). This includes:

  • Loops - Your analysis should acknowledge the number of iterations of the loop and the time complexity of the loop body (unless the loop body is very simple)
  • Recursion - Your analysis should acknowledge the number of recursive calls performed by the function, as well as the amount of work done per recursive call (not including the recursion itself)
  • Other functions - You should analyse the time complexity of any function used by the main function you are analysing, including functions that you did not write yourself. If the time complexity of a function is given (e.g., in a header file), you do not need to explain the time complexity, but you must still mention it.