L16 Introduction to Graphs

23
L16 – Introduction to Graphs Alice E. Fischer Spring 2019 Alice E. Fischer L16 – Graphs. . . 1/23 Spring 2019 1 / 23

Transcript of L16 Introduction to Graphs

Page 1: L16 Introduction to Graphs

L16 – Introduction to Graphs

Alice E. Fischer

Spring 2019

Alice E. Fischer L16 – Graphs. . . 1/23 Spring 2019 1 / 23

Page 2: L16 Introduction to Graphs

Outline

1 GraphsDefinitionGraph ApplicationsGraph Representations

2 Graph Implementation

Alice E. Fischer L16 – Graphs. . . 2/23 Spring 2019 2 / 23

Page 3: L16 Introduction to Graphs

Graphs

Graphs

Definitions, Terminology, and ExamplesApplications

Graph RepresentationsTopological Sort Algorithm

Alice E. Fischer L16 – Graphs. . . 3/23 Spring 2019 3 / 23

Page 4: L16 Introduction to Graphs

Graphs Definition

What is a Graph?

A graph is

A collection of nodes, with labels, often single letters, together with acollection of edges. Each edge connects two nodes.

A directed graph has edges that go in only one direction (arrows).

An undirected graph has bi-directional edges (simple lines).

The edges in a graph may be weighted or not. A weight representsthe cost of moving from one end of the edge to the other.

Alice E. Fischer L16 – Graphs. . . 4/23 Spring 2019 4 / 23

Page 5: L16 Introduction to Graphs

Graphs Definition

Directed and Weighted .. or not

Undirected, unweighted Weighted Directed

A

J C

H

G

FE

B

D

A

J C

H

G

FE

B

D

3

241

324

15

32 4

1

2

5

4

3

6

A

J C

H

G

FE

B

D

Andy works with Bob 1 hour from Ann Arbor Bill supervises AnnJake, and Gina to Grand Rapids Charles, and Ed

Alice E. Fischer L16 – Graphs. . . 5/23 Spring 2019 5 / 23

Page 6: L16 Introduction to Graphs

Graphs Definition

Subgraphs

A subgraph is any subset of the nodes of a graph, and the edges thatconnect them. The diagram shows two subgraphs (blue and orange) of anundirected graph.

A

J C

G

FE

D

B

H

Subgraphs with only one or two outside connections are of interest,especially in applications that involve choosing the location for resources.

Alice E. Fischer L16 – Graphs. . . 6/23 Spring 2019 6 / 23

Page 7: L16 Introduction to Graphs

Graphs Definition

Acyclic Graphs have no Cycles

A cycle is a path through the nodes that permits you to walk around andaround. This directed graph has two short cycles (red and blue edges) anda longer cycle that goes through H F D, and E.

A

J C

H

G

FE

B

D

Many graph problems involve the existence (or absence) of cycles.

Alice E. Fischer L16 – Graphs. . . 7/23 Spring 2019 7 / 23

Page 8: L16 Introduction to Graphs

Graphs Definition

Sources and Sinks

In a directed graph, a source is a node with no predecessors, and a sink isa node with no successors.

A

J C

H

GF E

B

D

The green node is a source, the red nodes are sinks.

Alice E. Fischer L16 – Graphs. . . 8/23 Spring 2019 8 / 23

Page 9: L16 Introduction to Graphs

Graphs Definition

Connected Components

In some graphs, all components are connected to the others. Here is agraph where that is not true: the blue components are not connected tothe pink ones.

A

J

E

K

D

L

B

M

C

N

Often, it is not obvious that a graph is disconnected. There is analgorithm for finding the connected components in a graph.

Alice E. Fischer L16 – Graphs. . . 9/23 Spring 2019 9 / 23

Page 10: L16 Introduction to Graphs

Graphs Definition

Spanning Tree

A spanning tree is a tree superimposed upon a graph. This tree uses some,but not all, of the graph’s edges, and does not have cycles.

A spanning tree is minimum if the total weight of all its edges is ≤ thetotal weights of all other spanning trees.

If a graph has more than one connected component, then it needs morethan one spanning tree to cover it. We call this set a spanning forest.

A

J

E

K

D

L

B

M

C

N

Alice E. Fischer L16 – Graphs. . . 10/23 Spring 2019 10 / 23

Page 11: L16 Introduction to Graphs

Graphs Definition

Bipartite Graphs have Two Kinds of Nodes

A special but useful kind of graph has two kinds of nodes, and every edgegoes from a node of one kind to an node of the other kind.

A

J

E

K

D

L

B

M

C

N

Alice E. Fischer L16 – Graphs. . . 11/23 Spring 2019 11 / 23

Page 12: L16 Introduction to Graphs

Graphs Graph Applications

Graph Problems

Many practical and mathematical problems are modeled by graphs

The traveling salesman problem.

Routes from a warehouse to all the retail stores.

Roads and intersections (Google maps).

Friend relationships (FaceBook).

Tasks and subtasks in a construction project.

Flow optimization on a network.

Placement of caches in a distributed data base.

Some graph problems can be solved in a reasonable amount of time(polynomial time), for others (called NP-complete problems), no algorithmexists that is better than “try all possibilities”.

Alice E. Fischer L16 – Graphs. . . 12/23 Spring 2019 12 / 23

Page 13: L16 Introduction to Graphs

Graphs Graph Representations

Representation of a Graph

Two representations are commonly used for graphs: matrices or a list ofnodes with lists of adjacent nodes.

We look first at the matrix representation, which is appropriate for densegraph (those with many edges).

The rows of the matrix represent a node and its outgoing edges.

The columns represent the node and its incoming edges.

For an unweighted graph, each matrix cell contains a 1 or a 0 sayingwhether or not the edge is present.

For a weighted graph, each matrix cell contains the weight.(Sometimes, ∞ is used to indicate a missing edge.)

Alice E. Fischer L16 – Graphs. . . 13/23 Spring 2019 13 / 23

Page 14: L16 Introduction to Graphs

Graphs Graph Representations

Matrix Representation of a Graph

The matrix on the left represents an undirected graph with weightededges. These matrices are always symmetric around the main diagonal.

On the right, we represent a directed graph with unweighted edges. Theedges are represented by a boolean value (1/0), where only the 1 valuesare shown. The matrix for a directed graph is not symmetric.

Alice E. Fischer L16 – Graphs. . . 14/23 Spring 2019 14 / 23

Page 15: L16 Introduction to Graphs

Graphs Graph Representations

The Adjacency List Representation

Use this representation for sparse graphs and graphs that can change.

Each node has a name and an adjacency list, and may have otherassociated information.

The main data structure is a map of nodes.

A node is stored in the map with its name, and can later be found byname.

An adjacency list is a vector of edges from one node (the fromNode)to other nodes (the toNodes).

If the graph is weighted, each edge has a weight as well as afromNode and a toNode

Alice E. Fischer L16 – Graphs. . . 15/23 Spring 2019 15 / 23

Page 16: L16 Introduction to Graphs

Graphs Graph Representations

An Undirected, Weighted Graph

The matrix representation of this graph is shown on the left. Comparethat to the adjacency list representation on the right.

Alice E. Fischer L16 – Graphs. . . 16/23 Spring 2019 16 / 23

Page 17: L16 Introduction to Graphs

Graphs Graph Representations

A Directed, Unweighted Graph

The matrix representation of this graph is shown on the left. Comparethat to the adjacency list representation on the right.

Alice E. Fischer L16 – Graphs. . . 17/23 Spring 2019 17 / 23

Page 18: L16 Introduction to Graphs

Graph Implementation

Graph Implementation

Adjacency List Representation: ClassesBuilding a Graph

The Code

Alice E. Fischer L16 – Graphs. . . 18/23 Spring 2019 18 / 23

Page 19: L16 Introduction to Graphs

Graph Implementation

Adjacency List Representation: Classes

Classes that, together, implement a graph structure:

Graph: a map of Nodes connected by Edges.

Edge: two node names and a weight.

Node: an adjacency vector. For some algorithms, other fields areadded.

Container templates used:

stl::map is used for the set of Nodes, indexed by the node name.

stl::vector is used for the adjacency lists.

stl::vector is used with the added heap functions for a sorting edges.

QueueT is used for breadth-first search.

Alice E. Fischer L16 – Graphs. . . 19/23 Spring 2019 19 / 23

Page 20: L16 Introduction to Graphs

Graph Implementation

What is a Map?

We use a map to organize a data set that must be searched often.

A map is an associative container data structure.

You store pairs in the map, where each pair consists of a data objectand an indexing key.

To retrieve a data object later, you execute find( key ).

The programmer can locate an object without writing a search loop.

In C++, the map template is implemented efficiently, with O(log(n))complexity for insertion and search. (Probably a red-black tree).

Imagine implementing Google Maps, with hundreds of thousands of cities(nodes). We want the city-nodes stored in an O( log(n) ) container like abalanced tree, not in a O( n ) container like a vector or linked list.

Alice E. Fischer L16 – Graphs. . . 20/23 Spring 2019 20 / 23

Page 21: L16 Introduction to Graphs

Graph Implementation

Making a Map of Nodes

We use a map<string, Node> to store the Nodes in our Graph.

To use the map, we need an iterator:map<string, Node>::iterator p;

We insert pairs of a C++ string and a Node: pair<string, Node>

We will input a name and use it BOTH in the pair and to call theNode constructor.

string name = "Nan";

make_pair( name, Node(name) );

make_pair() makes a pair, then returns a second pair consisting ofthe pair it made and a boolean success/failure code. To get aniterator pointing to the pair we want, select .first:

nodeMap.insert(item).first;

For simplicity, in this program we ignore the success/failure code.Good practice would be to check it and call fatal() if it is false.

Alice E. Fischer L16 – Graphs. . . 21/23 Spring 2019 21 / 23

Page 22: L16 Introduction to Graphs

Graph Implementation

Using a Map of Nodes

We made the map so that we could easily and efficiently find any node inthe graph, given its name.

To locate a node, use map::find(), which returns an iterator to a pair:map<string, Node>::iterator p;

p = nodeMap.find(name);

If the node was not in the map, find() returns nodeMap.end().if (p == nodeMap.end()) { // name not found in map

“Not found” is normal inside the Graph constructor but is a fatalerror when it happens in the middle of an algorithm.

Alice E. Fischer L16 – Graphs. . . 22/23 Spring 2019 22 / 23

Page 23: L16 Introduction to Graphs

Graph Implementation

Building a Graph

To build a Graph data structure:

Input file, first line, says whether the graph is directed or undirected.

Other input lines specify one edge each: names of the fromNode andtoNode, and the edge’s weight

For an unweighted graph, the file should give weight=1 for all edges.

When an edge is read, we insert both from and to node names intothe map, if they are not already there.

Then we use the from name to locate the node in the node map, andappend the edge to the adjacency list of the fromNode.

For undirected graphs, we also append the edge to the adjacency listof the toNode.

Alice E. Fischer L16 – Graphs. . . 23/23 Spring 2019 23 / 23