This lesson introduces a new data structure: graphs. Graphs are extremely useful, both for modeling certain types of data, and for enabling certain algorithms. In fact, trees, which we've been studying previously, are themselves a type of graph. Graphs are also great for practice with recursion, and you'll also work a bit with them on the MP. So let's get started!
Wikipedia defines a graph as:
A graph data structure consists of a finite (and possibly mutable) set of vertices (also called nodes or points), together with a set of unordered pairs of these vertices for an undirected graph or a set of ordered pairs for a directed graph. These pairs are known as edges (also called links or lines), and for a directed graph are also known as edges but also sometimes arrows or arcs. The vertices may be part of the graph structure, or may be external entities represented by integer indices or references.
Let's look at some diagrams that will help visualize this new data structure, and introduce some important terminology.
Graphs can be used to model a variety of real-world entities, which is part of what makes them so useful to computer scientists. Some examples include:
Let's look at these example a bit more:
Depending on the properties of their edges, graphs can be directed or undirected, weighted or unweighted. We'll focus our attention on undirected unweighted graphs. But let's discuss the differences briefly.
We've discussed trees previously, and it turns out that trees are one specific type of graph. Now that we have been introduced to graphs, we can define a tree more precisely.
Previous we introduced recursion, a problem solving technique that works by breaking down large problems into smaller pieces, solving them, and then combining the results. Graphs are another data structure that we frequently will examine recursively. Let's see why:
In addition, like trees, compared to lists and arrays and
Strings, graphs can be hard to work with using iterative solutions!
Recursion is a much better approach...
To help you prepare for our next homework problem, let's discuss the recursive approach to counting the number of nodes in a graph. Specifically, we'll review the idea of graph traversal, and how not to get stuck along the way.