The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
9.4. Working with Graphs
A graph is a collection of nodes that interconnect with each other arbitrarily. (A tree is a special case of a graph.) We will not delve deeply into the subject of graphs because the theory and terminology can have a steep learning curve. Before long, we would find ourselves wandering out of the field of computer science entirely and into the province of mathematicians. Yet graphs do have many practical applications. Consider any ordinary highway map with highways connecting cities, or consider a circuit diagram. These are both best represented as graphs. A computer network can be thought of in terms of graph theory, whether it is a LAN of a dozen systems or the Internet itself with its countless millions of nodes. When we say graph, we usually mean an undirected graph. In naive terms, this is a graph in which the connecting lines don't have arrows; two nodes are either connected or they are not. By contrast, a directed graph or digraph can have "one-way streets"; just because node x is connected to node y doesn't mean that the reverse is true. (A node is also commonly called a vertex.) Finally, a weighted graph has connections (or edges) that have weights associated with them; these weights may express, for instance, the "distance" between two nodes. We won't go beyond these basic kinds of graphs; the interested reader can refer to numerous references in computer science and mathematics. In Ruby, as in most languages, a graph can be represented in multiple ways; for example, a true network of interconnected objects or a matrix storing the set of edges in the graph. We will look at both of these as we show a few practical examples of manipulating graphs. 9.4.1. Implementing a Graph as an Adjacency Matrix
The example here builds on two previous examples. In Listing 9.3 we implement an undirected graph as an adjacency matrix, using the ZArray class (see section 8.1.26, "Establishing a Default Value for New Array Elements") to make sure that new elements are zero and inheriting from the triMatrix (see section 8.1.7, "Using Specialized Indexing Functions") to get a lower triangular matrix form. Listing 9.3. Adjacency Matrix
Note that in the kind of graph we are implementing here, a node cannot be connected to itself, and two nodes can be connected by only one edge. We provide a way to specify edges initially by passing pairs into the constructor. We also provide a way to add and remove edges and detect the presence of edges. The vmax method returns the highest-numbered vertex in the graph. The degree method finds the degree of the specified vertexthat is, the number of edges that connect to it. Finally, we provide two iterators, each_vertex and each_edge. These iterate over edges and vertices, respectively. 9.4.2. Determining Whether a Graph Is Fully Connected
Not all graphs are fully connected. That is, sometimes "you can't get there from here"; there may be vertices that are unreachable from other vertices no matter what path you try. Connectivity is an important property of a graph to be able to assess, telling whether the graph is "of one piece." If it is, every node is ultimately reachable from every other node. We won't explain the algorithm; the interested reader can refer to any discrete math book. But we offer the Ruby method in Listing 9.4. Listing 9.4. Determining Whether a Graph is Fully Connected
I've referenced a method here (euler_path?) that you haven't seen yet. It is defined in section 9.4.4, "Determining Whether a Graph Has an Euler Path." A refinement of this algorithm could be used to determine the set of all connected components (or cliques) in a graph that is not overall fully connected. I won't cover this here. 9.4.3. Determining Whether a Graph Has an Euler Circuit
There is no branch of mathematics, however abstract, which may not some day be applied to phenomena of the real world. Nikolai Lobachevsky Sometimes we want to know whether a graph has an Euler circuit. This term comes from the mathematician Leonhard Euler who essentially founded the field of topology by dealing with a particular instance of this question. (A graph of this nature is sometimes called a unicursive graph since it can be drawn without lifting the pen from the paper or retracing.) In the German town of Königsberg, there was an island in the middle of the river (near where the river split into two parts). Seven bridges crisscrossed at various places between opposite shores and the island. The townspeople wondered whether it was possible to make a walking tour of the city in such a way that you would cross each bridge exactly once and return to your starting place. In 1735, Euler proved that it was impossible. This, then, is not just a classic problem, but the original graph theory problem. And, as with many things in life, when you discover the answer, it is easy. It turns out that for a graph to have an Euler circuit, it must possess only vertices with even degree. Here we add a little method to check that property: class Graph def euler_circuit? return false if !connected? for i in 0..@max return false if degree(i) % 2 != 0 end true end end mygraph = Graph.new([1,0],[0,3],[2,1],[3,1],[3,2]) flag1 = mygraph.euler_circuit? # false mygraph.remove 1,3 flag2 = mygraph.euler_circuit? # true 9.4.4. Determining Whether a Graph Has an Euler Path
An Euler path is not quite the same as an Euler circuit. The word circuit implies that you must return to your starting point; with a path, we are really only concerned with visiting each edge exactly once. The following code fragment illustrates the difference: class Graph def euler_path? return false if !connected? odd=0 each_vertex do |x| if degree(x) % 2 == 1 odd += 1 end end odd <= 2 end end mygraph = Graph.new([0,1],[1,2],[1,3],[2,3],[3,0]) flag1 = mygraph.euler_circuit? # false flag2 = mygraph.euler_path? # true 9.4.5. Graph Tools in Ruby
There are a few tools known to exist in the Ruby community. Most of these have some limited functionality for dealing with directed and undirected graphs. They can be found with a search of RAA (http://raa.ruby-lang.org) and Rubyforge (http://rubyforge.org). Most of them have names such as RubyGraph, RGraph, and GraphR, and they are fairly immature. If you are interested in the excellent GraphViz package, which renders complex graphs both as images and as printable Postscript, there are at least two workable interfaces to this software. There is even a GnomeGraphwidget, which according to the documentation "can be used by a Ruby Gnome application to generate, visualize and interact with graphs." We haven't looked at it, however; be warned it is pre-alpha. In short, there may be a need for tools of this sort. If so, I urge you to write your own, or better, to join an existing project. If working with graphs becomes easy enough, it may be one of those techniques we wonder how we did without. |
Категории