23
Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between two vertices. We can represent graphs pictorially by drawing points (vertices) and connecting them with lines (edges). However the graph is independent of the way it is represented. J L K M J L K M Two representations of the same graph

Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Embed Size (px)

Citation preview

Page 1: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Graphs

Graphs are collections of vertices and edges.

Vertices are simple objects with associated names and other properties.

Edges are connections between two vertices.

We can represent graphs pictorially by drawing points (vertices) and connecting them with lines (edges). However the graph is independent of the way it is represented.

J

L

K

M

J

LK

M

Two representations of the same graph

Page 2: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Paths

A path is a list of vertices in which successive vertices are connected by edges in a graph. Example: BAFEG is a path.

J

L

K

M

A

B C G

F

D E

H I

Page 3: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Connected Graphs

A graph is connected if there is a path from every node to every other node in the graph1. A graph that is not connected is made up of connected components. The graph below has three connected components.

J

L

K

M

A

B C G

F

D E

H I

1 Intuitively, if the vertices were physical objects and the edges were strings connecting them,a connected graph would stay in one piece if picked up by any vertex.

Page 4: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Paths and Cycles

A simple path is a path in which no vertex is repeated. Examples:BAFE is a simple path. BAFEGAC is not a simple path

A cycle is a simple path except that the first and last vertex are the same (a path from a point back to itself). Example: AFEGA is a cycle.

J

L

K

M

A

B C G

F

D E

H I

Page 5: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Trees and Forests

A graph with no cycles is called a tree. A group of disconnected trees is called a forest. The figure below represents a forest of three disconnected trees.

J

L

K

M

A

B C G

F

D E

H I

Page 6: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Spanning Trees

A spanning tree of a graph is a subgraph that contains all the vertices but only enough of the edges to form a tree.

The figure below shows a graph (left) and one of its possible spanning trees (right).

A

B C G

F

D E

A

B C G

F

D E

Page 7: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Spanning Trees

If we add any edge to a spanning tree, it must form a cycle (since there is already a path between the two vertices that it connects).

A tree with V vertices has exactly V-1 edges. If a tree has less than V-1 edges, it can't be connected. If it has more than V-1 edges, it must have a cycle. (But if it has exactly V-1 edges it need not be a tree!).

A

B C G

F

D E

A

B C G

F

D E

Page 8: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Sparse and Complete Graphs

V: number of verticesE: number of edges

E can range anywhere between 0 and 1/2(V)(V-1)

Graphs with all edges present are called complete graphs.

Graphs with relatively few edges (say less than VlogV) are called sparse.

Graphs with relatively few of the possible edges missing are called dense.

J

L

K

M

J

L

K

M

J

L

K

M

Complete Dense Sparse

Page 9: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Directed, Undirected, and Weighted Graphs

So far we've dealt with undirected graphs, the simplest type.

In weighted graphs, integers (weights) are assigned to each edge to represent, say, distances or costs.

In directed graphs, edges are “one-way”: an edge may go from J to K but not from K to J.

Directed weighted graphs are sometimes called networks.

J

L

K

M

J

L

K

M

Directed Weighted Directed weighted (network)

2

1 34

J

L

K

M

2

1 346

57

Page 10: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Graph Representation

We will look at two data structure representations of graphs.

● Adjacency matrix representation● Adjacency structure representation

Usually, the choice of representation depends on whether the graph in question is dense or sparse, however this also depends on the nature of the operations to be performed as well.

The first step is to map the vertex names to integers. This is to allow accessing vertex information through an array index. Throughout, we will assume the existance of a function index which, when called with a vertex name, returns the integer representation of that vertex. We will also assume the existance of a function name which when called with a vertex index, returns the vertex name. In the examples to follow, we map vertices with single-character names to integers.

Page 11: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Adjacency Matrix Representation

A

B C G

F

D E

A B C D E F GA 1 1 1 0 0 1 1B 1 1 0 0 0 0 0C 1 0 1 0 0 0 0D 0 0 0 1 1 1 0E 0 0 0 1 1 1 1F 1 0 0 1 1 1 0G 1 0 0 0 1 0 1

This representation is suitable for dense graphs.

A VxV array a of boolean values is maintained, with a[x,y] set to true if there is an edge from vertex x to vertex y and false otherwise.

Each edge is represented by two bits: a[x,y] and a[y,x].

Obviously this is a symmetric matrix and even though we could store only half of it, it is inconvenient to do so from an indexing viewpoint.

Note that it is usually convenient to assume that there's an “edge” fromeach vertex to itself, so a[x,x] is set to true. (In some cases, it is moreconvenient to set the diagonal elements to false.)

Page 12: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Adjacency Structure Representation

This representation is suitable for sparse graphs.

All vertices connected to each vertex are listed on an adjacency list for that vertex. This can be easily done with linked lists.

A

B C G

F

D E

A B C D E E F G

F A A F F D A A

B E D F D E

C G G E

GNote that final outcome of adjacency lists depend on how the edges were input. For example, for adjacency list for ‘A’ above, the input edges were AG, AC, AB, AF.

Page 13: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Constructing Adjacency Lists

#include <iostream>using namespace std;

const int maxV = 1000;

typedef struct node { int v; node* next;} node, *nodePtr;

nodePtr z = 0;int V=0, E=0; // vertex and edge countnodePtr adj[maxV]; // adjacency list

int index(int i){ return i;}

Page 14: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Con

stru

ctin

g A

djac

ency

Lis

tsvoid load(){ int j, x, y; nodePtr t;

int v1, v2; // can be other types. see 'index'

cin >> V; // get number of vertices cin >> E; // get number of edges

cout << V << " vertices, " << E << " edges." << endl;

z = new(node); z->next = z;

// init lists for (j=0; j<V; j++) adj[j] = z;

// read edges for (j=0; j<E; j++) { cin >> v1; cin >> v2;

// get edge vertices x = index(v1); y = index(v2);

cout << "Edge " << j << ": " << x << ", " << y << endl;

t = new node; t->v = x; t->next = adj[y]; adj[y] = t; t = new node; t->v = y; t->next = adj[x]; adj[x] = t; }}

Page 15: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Con

stru

ctin

g A

djac

ency

Lis

tsvoid list(){ int i; nodePtr t;

for (i=0; i<V; i++) { t = adj[i]; if (t != z) cout << i << " connected to "; while (t != z) { cout << t->v << ((t->next == z) ? " " : ", "); t = t->next; } cout << endl; }}

Page 16: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Depth-First Search

When dealing with graphs, many questions can arise:

Is the graph connected? If not, what are its connected components?Does the graph have a cycle?

To answer these kinds of questions, depth-first search is used.

Page 17: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Depth-First Search

void dfs() { int id=0, k; int val[maxV];

for (k=0; k<V; k++) val[k] = 0;

for (k=0; k<V; k++) if (!val[k]) visit(val, k, id);}

Page 18: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Depth-First Search

void visit(int* val, int k, int & id){ nodePtr t;

cout << "visit: visiting node " << k << endl;

val[k] = ++id; t = adj[k];

while (t != z) { if (val[t->v] == 0) visit(val, t->v, id);

t = t->next; }}

Page 19: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Depth-First Search

DFS for a graph represented with adjacency lists requires time proportional to V + E.

We set each of the V val values (hence the V term) and we examine each edge twice (hence the E term).

DFS for a graph represented with an adjacency matrix require time proprotional to V2 (every bit in the matrix is checked).

Page 20: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Non-Recursive Depth-First Search

We can implement DFS non-recursively. We simply replace the frame stack with our own stack structure.

Our dfs() function two slides back remains almost the same, however the function visit() is now made non-recursive.

void dfs() { int id=0, k; int val[maxV];

// stack_init() // initialize the stack

for (k=0; k<V; k++) val[k] = 0;

for (k=0; k<V; k++) if (!val[k]) visit(val, k, id);}

Page 21: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Non-recursive Depth-First Searchvoid visit(int* val, int k, int & id){ nodePtr t;

cout << "visit: visiting node " << k << endl;

stack_push(k);

do { k = stack_pop(); val[k] = ++id; t = adj[k];

while (t != z) { if (val[t->v] == 0) { stack_push(t->v); val[t->v] = -1; }

t = t->next; } } while (! Stackempty());}

Page 22: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

Breadth-First Search

Rather than use a stack to hold vertices, as in DFS, here we use a queue. This leads to a second way of graph traversal, known as breadth-first search.

To implement BFS, simply change stack operations to queue operations.

Changing the data structure this way affects the order in which the nodes are visited.

Page 23: Graphs Graphs are collections of vertices and edges. Vertices are simple objects with associated names and other properties. Edges are connections between

DFS v. BFS

In terms of vertex exploration, how do you think DFS and BFS differ?

DFS: Explore deeper into the graph frontier (process closer vertices only after farther-away vertices have been explored).

BFS: Sweep around starting point, exploring deeper only after all surrounding vertices in vicinity have been explored

Order of traversal in either method is highly dependent on the order in which the vertices appear in the adjacency lists.