2. GRAPH
A data structure that consists of a set of
nodes(vertices) a set of edges that
relate the nodes to each other.
The of edged describes relationships
among the vertices.
A graph G is defined as follows.
G=(V,E)
V(G): a finite ,nonempty set of vertices
E(G): a set of edges (pairs of vertices)
6. Graph terminology
Adjacent nodes: two nodes are said to adjacent if they are
connected by an edge
Path: a sequence of vertices that connect two
Complete graph : a graph in which every vertex is directly
connected to every other vertex.
4 5 is adjacent to 45
7. Cycle : a cycle is a simple path with the same
start and end vertex.
Degree : the degree of vertex is the no. of
edges incident on vertex.
e.g ., d(a)=3, d(d)=2.
a
s
r
d
v t h
8. loops: edges connect a vertex to itself
Simple graph a simple graph has no loop ,no
multiedge.
Complete graph : a graph in which every vertex is
directly connected to every other vertex.
5
9. Connections
An undirected graph are connected if there is a
path between any two vertices
Directed graph are strongly connected if there is a
path from any one vertex to any other
Directed graph are weakly connected if there is a
path between any two vertices
ignoring direction .
A complete graph has an edge between every pair of
vertices.
10. Graph searching
Problem: find a path between two nodes
of the graph .
Method:
1: depth-first-search (DFS)
2: breadth-first-search (BFS)
11. Depth-first-search (DFS)
What is the idea behind DFS?
travel as far as you can down a path.
back up as little as possible when you reach a “dead
end”(i.e., next vertex has been “marked” or there is no next vertex)
DFS can be implemented efficiently using a
stack
12. DFS…..
set found to false
stack.Push(stackVertex)
DO
stack.Pop(vertex)
IF vertex == endVertex
set found to true
ELSE
push all adjacent vertices onto stack
WHILE !stack.IsEmpty()AND !found
IF(!found)
Write “path does not exist”.
13. Breadth-first-searching
(BFS)
what is idea behind BFS ?
Look at all possible paths at the same the same depth
You go at a level
Back up as far as possible when you reach a “dead end”
(i.e., next vertex has been “marked” or there is no next vertex)