48
Chapter 11. Graphs [INA240] Data Structures and Practice Youn-Hee Han http://link.kut.ac.kr

[INA240] Data Structures and Practice

Embed Size (px)

DESCRIPTION

Where We Are? Graph Tree Binary Tree Binary Search Tree AVL Search Tree Splay Tree Heap Multiway Trees

Citation preview

Page 1: [INA240] Data Structures and Practice

Chapter 11. Graphs

[INA240] Data Structures and PracticeYoun-Hee Han

http://link.kut.ac.kr

Page 2: [INA240] Data Structures and Practice

Where We Are?

Tree Binary Tree Binary Search Tree

Heap

Multiway Trees

Graph

AVL Search TreeSplay Tree

Page 3: [INA240] Data Structures and Practice

1. Basic ConceptsGraph

a collection of nodes (vertices) and lines (edges, arcs) The lines in a graph are called

Undirected graphs: edge Directed graphs (Digraph): arc (or directed edge)

edge arc

Page 4: [INA240] Data Structures and Practice

1. Basic ConceptsFirst use of graphs: Köenigsberg bridge problem [Leonhard Euler 1736]

Starting from land area, is it possible to return to starting location after walking across each of the bridges exactly once?

Eulerian walk (circuit)

Eulerian walk is possible if and only if the degree of each vertex is even

C

B

A Da b

dc

f

g

e

Page 5: [INA240] Data Structures and Practice

1. Basic Concepts

Map of Kaliningrad in Euler's time (1736)

Kaliningrad, present

Page 6: [INA240] Data Structures and Practice

1. Basic ConceptsExamples of Graph

0

6543

21

0

1 2

3

G1 G2

V(G2)={0,1,2,3,4,5,6}E(G2)={(0,1), (0,2), (1,3), (1,4), (2,5), (3,6)}

V(G1)={0,1,2,3} E(G1)={(0,1), (0,2), (0,3), (1,2), (1,3), (2,3)}

Page 7: [INA240] Data Structures and Practice

1. Basic ConceptsTerminologies

Path: sequence of vertices in which each vertex is adjacent to next one

Ex) ABCE, ABEF in Figure (a) Ex) ABCE, ECBA, ABEF, FEBA in Figure (b)

Two vertices are adjacent (or neighbors) if there is a direct path connecting them

The vertices share a path of length 1 connecting them. B is adjacent to A D is not adjacent to F

Data Structure7(a) (b)

Page 8: [INA240] Data Structures and Practice

1. Basic ConceptsTerminologies

Cycle: a path whose start and end vertices are the same

In figure (a), no cycle is found In figure (b), BCDEB is cycle In figure (c), ABC is cycle

Cyclic Graph is a graph with a cycle Loop: single arc begins and ends at the same vertex

Data Structure8

(a) (b) (c)

Page 9: [INA240] Data Structures and Practice

1. Basic ConceptsTerminologies

Two vertices are connected if there is a path between them

A graph is connected if there is a path from any vertex to any other vertex, ignoring direction

Directed graph… It is strongly connected if there is a path from each vertex to

every other vertex, considering direction Otherwse, it is weakly connected

Undirected graph is always stong connected if it is connected

A graph is disjoint if it is not connected

Data Structure9

Page 10: [INA240] Data Structures and Practice

1. Basic ConceptsTerminologies

Connected Graph - (a), (b), (d), (e), (f) Disjoint Graph – (c) Complete Graph ( 완전 그래프 ) – (e), (f)

모든 Node 들 간에 1:1 로 직접 연결된 Edge 를 지닌 그래프 모든 Node 들이 서로 인접 (Adjacent) 하다 . a graph that has the maximum # of edges

0

1 2

3(f)

Data Structure10

Page 11: [INA240] Data Structures and Practice

1. Basic ConceptsTerminologies

G’(V’,E’) is subgraph of G(V, E) V(G ’) V(G ) and E(G ’) E(G )

Subgraph G’ 는 그래프 G 의 일부 Node 들과 이들을 연결하는 Edge 만을 취하여 만든 부분 그래프

G1 subgraphs of G1

Data Structure11

Page 12: [INA240] Data Structures and Practice

1. Basic ConceptsTerminologies

The degree of a vertex is the number of lines incident to it.

In Figure (a), the degree of vertex B is 3 and the degree of vertex E is 4

The outdgree and indegree of a vertex In Figure (a), the indegree of vertex B is 1 and its

outdegree is 2 In Figure (b), the indegree of vertex E is 3 and its

outdegree is 1

Data Structure12

Page 13: [INA240] Data Structures and Practice

1. Basic ConceptsTerminologies

그래프의 동일성 아래 두 그래프는 동일하다 (or 일치한다 ) = homogeneous

Node 들 상호간의 공간적인 위치 관계 (Topology) 는 중요하지 않다 같은 Node 집합을 지니고 있고 그들 사이에 Edge 연결 상태가 동일하면

두 그래프는 일치한다 .

Data Structure13

Page 14: [INA240] Data Structures and Practice

Data Structure14

1. Basic Concepts그래프와 트리

Tree 연결된 (Connected) & 사이클 없는 (Acyclic) 그래프 V 개의 정점 , 항상 V-1 개의 간선 a graph in which any two vertices are connected by exactly one path

Page 15: [INA240] Data Structures and Practice

Data Structure15

1. Basic Concepts그래프와 트리

V 개의 Node 들에 대하여 V-1 개 보다 많은 Edge 가 존재하면 사이클이 존재 (Cyclic Graph) V-1 보다 적으면 절단 그래프 (Disjoint Graph)

Page 16: [INA240] Data Structures and Practice

2. OperationsInserting a vertex

Deleting a vertex

Data Structure16

Page 17: [INA240] Data Structures and Practice

2. OperationsInserting an edge

Deleting an edge

Find Vertex

Data Structure17

Page 18: [INA240] Data Structures and Practice

2. OperationsTraverse

Depth-first traversal – Goal Seeking process all of a vertex’s descendents before we move to

an adjacent vertex Use Stack!!!

Data Structure18

1. Push the first node into the stack2. Repeat until stack is empty 2-1) Pop a vertex 2-2) Process the vertex (mark the vertex) 2-3) Push all of adjacent vertices

Page 19: [INA240] Data Structures and Practice

2. OperationsTraverse

Depth-first traversal – Just Traverse All Vertex process all of a vertex’s descendents before we move to

an adjacent vertex Use Stack!!! (After Push…, Pop and Process)

Data Structure19

Page 20: [INA240] Data Structures and Practice

2. OperationsTraverse

Depth-first traversal – Just Traverse All Vertex Exercise: perform iterative DFS on this graph, starting

from red vertices Assume adjacency list is sorted in ascending order (

오름차순 )

V3

V2V1

V0

V6V4 V5

V7

Page 21: [INA240] Data Structures and Practice

2. OperationsTraverse

Breadth-first traversal – Just Traverse All Vertex process all adjacent vertices of a vertex before going to

the next level Use Queue!!!

Data Structure21

1. Enqueue the first node into the queue2. Repeat until queue is empty 2-1) Dequeue a vertex 2-2) Process the vertex (mark the vertex) 2-3) Enqueue all of adjacent vertices

Page 22: [INA240] Data Structures and Practice

3. Graph Storage StructuresAdjacency Matrix ( 인접 행렬 )

A vector (one-dimensional array) for a vertices and a matrix to store the edges

2 차원 행렬 : 2 차원 배열 - A[MAX][MAX] 직접 연결된 간선이 있으면 해당 값을 1(True)

Data Structure22

일종의 심볼 테이블

Page 23: [INA240] Data Structures and Practice

3. Graph Storage StructuresAdjacency Matrix ( 인접 행렬 )

무방향 그래프 (Undirected Graph) 인 경우 무방향 그래프의 인접행렬은 대각선을 중심으로 대칭 메모리 절약을 위해 배열의 반쪽 만을 사용할 수 있음

방향 그래프 (Directed Graph) 인 경우 대칭이 아님

Data Structure23

일종의 심볼 테이블

Page 24: [INA240] Data Structures and Practice

3. Graph Storage StructuresAdjacency Matrix ( 인접 행렬 )

인접행렬 표현을 위한 심볼 테이블 Node ID 를 배열 인덱스로 매핑 시키는 테이블 “a 에서 c 로 가는 Direct Edge 가 있는가 ?”

a 0 e 4 A[0][4] 가 1 이면 a 와 e 는 edge 존재

Data Structure24

Vertex 배열 인덱스

a 0b 1c 2d 3e 4

Page 25: [INA240] Data Structures and Practice

3. Graph Storage StructuresAdjacency List ( 인접 리스트 )

2-dimensional ragged ( 울퉁불퉁한 ) array to store the edges

Vertex list A singly linked list of the vertices in the list.

하나의 정점에 인접한 모든 노드를 연결 리스트 형태로 표시 , 또는 포인터 배열로 표시

경로에 관한 정보가 아님 . c 를 나타내는 A[2] 에 대한 연결 리스트가 deb 라고 해서 경로가

그렇다는 것은 아님

Data Structure25 Vertext list

Page 26: [INA240] Data Structures and Practice

3. Graph Storage StructuresAdjacency List ( 인접 리스트 )

Data Structure26

Page 27: [INA240] Data Structures and Practice

3. Graph Storage StructuresAdjacency List ( 인접 리스트 )

무방향 그래프 (Undirected Graph) 인 경우 하나의 간선에 대해 두 개의 노드가 나타남 . 인접 리스트의 노드 수는 간선 수의 2 배

방향 그래프 (Directed Graph) 인 경우 하나의 간선이 정확히 한번 나타남

Data Structure27

Page 28: [INA240] Data Structures and Practice

3. Graph Storage StructuresAdjacency Matrix vs. Adjacency List

정점 i 와 정점 j 가 인접해 있는가의 판단 인접행렬 (Adjacent Matrix) 이 유리

정점 i 에 인접한 모든 노드를 찾는 것에 대한 연산 인접 리스트 (Adjacent List) 가 유리

공간 면에서 인접행렬은 2V 개의 공간 , 인접 리스트는 2E 개의 공간이 필요

방향그래프인 경우 인접 리스트는 E 개의 공간만 필요

희소 그래프 , 조밀 그래프 간선 수가 적은 그래프를 희소 그래프 ( 稀少 , Sparse Graph) 간선 수가 많은 그래프를 조밀 그래프 ( 稠密 , Dense Graph) 희소 그래프일 수록 인접 리스트가 유리

Data Structure28

Page 29: [INA240] Data Structures and Practice

4. NetworksTree: a graph in which any two vertices are connected by exactly one path

Equivalent definitions G is connected and has no simple cycles. G has no simple cycles and, if any edge is

added to G, then a simple cycle is formed. G is connected and, if any edge is removed

from G, then it is not connected anymore. Equivalent conditions

G is connected and has n − 1 edges. G has no simple cycles and has n − 1

edges.

Page 30: [INA240] Data Structures and Practice

4. NetworksNetwork (Weighted graph ( 가중치 그래프 ))

a graph whose edges are weighted 용도 : 정점 사이를 이동하는데 필요한 비용이나 거리를 알아봄

Data Structure30

Page 31: [INA240] Data Structures and Practice

4. NetworksRepresentation of Weighted Graph

Data Structure31

Page 32: [INA240] Data Structures and Practice

4. NetworksSpanning Tree (of a connected, undirected graph G)

any tree that consists solely of edges in G that includes all the vertices in G

Spanning tree G’ is a minimal subgraph of G such that V(G’) = V(G) and G’ is connected Any connected graph with n vertices must have n-1

edges.

When a number of vertex is n, all connected graphs with n-1 edges are trees

G Spanning Trees of G

Tree: 연결된 (Connected) & 사이클 없는 (Acyclic) 그래프

Data Structure32

Page 33: [INA240] Data Structures and Practice

4. NetworksMinimum (Cost) Spanning Tree

Spanning tree of least cost (cost: sum of weights)

Minimum (Cost) Spanning Tree Algorithms Kruskal’s algorithm Prim’s algorithm Sollin’s algorithm

Study in Algorithm Class!!!!!

Data Structure33

Page 34: [INA240] Data Structures and Practice

4. NetworksPrim’s Algorithm – Example 1

Data Structure35

Page 35: [INA240] Data Structures and Practice

4. NetworksShortest Path Problem

In an edge-weighted graph (network), the weight of an edge measures the cost of traveling that edge.

For example, in a graph representing a network of airports, the weights could represent: distance, cost or time.

Such a graph could be used to answer any of the following:

What is the fastest way to get from A to B? Which route from A to B is the least expensive? What is the shortest possible distance from A to B?

Each of these questions is an instance of the same problem: The shortest path problem!

Data Structure37

Page 36: [INA240] Data Structures and Practice

4. NetworksShortest Path Problem

Given the graph we used in the previous topic, suppose we wish to find the shortest path from vertex 1 to vertex 13

Page 37: [INA240] Data Structures and Practice

4. NetworksShortest Path Problem

After some consideration, we may determine that the shortest path is as follows, with length 14

Other paths exists, but they are longer

Page 38: [INA240] Data Structures and Practice

23/5/5chapter25 40

Find a shortest path from station A to station B.-need serious thinking to get a correct algorithm.

A

B

4. NetworksShortest Path Problem

Application #1

Page 39: [INA240] Data Structures and Practice

4. NetworksShortest Path Problem Application #2

The Internet is a collection of interconnected computer networks

Information is passed through packets Packets are passed from the source, through routers,

to their destination Routers are connected to either:

individual computers, or other routers

These may be represented as graphs

Page 40: [INA240] Data Structures and Practice

4. NetworksShortest Path Problem Application #2

A visualization ofthe graph of therouters and theirvariousconnectionsthrough a portionof the Internet

http://en.wikipedia.org/wiki/Internet

Metrics for measuring the shortest path may include:- low latency (minimize time), or- minimum hop count (all edges have weight 1)

Page 41: [INA240] Data Structures and Practice

4. NetworksDijkstra algorithm

Given an (undirected) graph G=(V,E), determine a shortest path between any two nodes in a graph

Given a (directed) graph G=(V,E), determine a shortest path from v0 to each of the remaining vertices of G

v2

v0

v3 v5

v1 v4

20

50 10

315

3530

15

45 destination

path Length

v2 v0v2 10v3 v0v2v3 25v1 v0v2v3v1 45v4 v0v4 45v5 No path infiniteshortest paths starting from v0

10 20

Page 42: [INA240] Data Structures and Practice

4. NetworksDijkstra algorithm

Idea: starting from a source vertex v0, find the shortest paths to other vertices in stages

Let S : set of vertices to which the shortest path from v0 is found.

Initially, S = { v0 } Add a vertex into S at each stage

v0

S

v0S

v0

S

Page 43: [INA240] Data Structures and Practice

4. NetworksDijkstra algorithm

At each stage … Attach minimum distance T to a vertex v

T [w] = length of shortest path from v0 to v, going through vertices in S

Initially, T [v] = cost(v0, v) (mostly infinity) After adding u to S, adjust distance of vertices not in S

T [v] = min(T [v], T [u] + cost(u,v))

v0

S

xu

v0

S

xu

v v

… …

S 에 들어올 후보 노드는 S 에 속해 있지 않으면서distance T 값이 가장 작은 노드

Page 44: [INA240] Data Structures and Practice

4. NetworksDijkstra’s algorithm (source vertex: v)

1 function Dijkstra(Graph, source): 2 for each vertex v in Graph: // Initializations 3 T[v] := infinity // Unknown distance T from source to v 4 previous[v] := undefined // Previous node in optimal path from source 5 T[source] := 0 // Distance T=0 from source to source 6 Q := the set of all nodes in Graph // All nodes in the graph are unoptimized - thus are in Q 7 while Q is not empty: // The main loop 8 u := vertex in Q with smallest T[] 9 if T[u] = infinity: 10 break // all remaining vertices are inaccessible 11 remove u from Q 12 for each neighbor v of u: // where v has not yet been removed from Q. 13 alt := T[u] + cost(u, v) 14 if alt < T[v]: // redefine the distance V15 T[v] := alt 16 previous[v] := u 17 return previous[]

Page 45: [INA240] Data Structures and Practice

4. NetworksDijkstra’s algorithm (An Example)

Page 46: [INA240] Data Structures and Practice

4. NetworksDijkstra’s algorithm (An Example – Cont.)

Page 47: [INA240] Data Structures and Practice

4. NetworksExercise Find shortest paths from vertex 1 to other

vertices.

Page 48: [INA240] Data Structures and Practice

Data Structure50

기말고사 일시 : 6 월 16 일 오후 7 시 장소 : B 동 315 시험 범위 : 6 장 ~ 11 장