Vous êtes sur la page 1sur 18

Applications of BFS & DFS

 BFS:
 Shortest path algorithm(Dijkstra’s algorithm)
 Minimum spanning tree(Prim’s and Kruskal’s algorithm)

 DFS:
 Undirected graph
 Directed graph
 Bi-connectivity (Articulation Points)
 Euler Circuits
 Strong Components

1
Euler Circuits

2
Euler Circuits(Conti…)

3
The Disjoint Set ADT

4
Issues:

• The equivalence relation


• The dynamic equivalence problem
• Disjoint set algorithms
• Smart union algorithms
• Path Compression algorithms

5
Equivalence Relations
• A relation R is defined on a set S if for every pair
of elements (a,b), a,bS, a R b is either true or
false. If a R b is true, then we say that a is
related to b.
• An equivalence relation is a relation R that
satisfy three properties:
– (reflexive) a R a, for all a  S.
– (symmetric) a R b if and only if b R a.
– (transitive) a R b and b R c implies that a R c.

6
Disjoint Sets Algorithms
• Make the input a collection of N sets, each
with one element.
– All relations (except reflexive) are false;
– Each set has a different element: SiSj= => it
makes the sets disjoint.
• Find operation: returns the name of the set
containing a given element.
• Add operation (e.g., add relation a~b)
– Check if a and b are already related: if they are in
the same equivalence class.
– If not, apply “union”: merge the two equivalence
classes containing a and b into a new equivalence
class. 7
Example:
On a set of subsets, the three operations
amount to
• Create a set of n disjoint subsets with
every node in its own subset
• Test wheter A and B are in the same
subset
• If A and B are in the same subset, then do
nothing, else unify the subsets to which A
and B belong
8
coding
void union(Node A, Node B)
{
if (find(A) != find(B))
union(A, B);
}

9
10
11
12
Algorithm

Void DisjSets::unionSets(root1, root2)


{
s[root2]=root1;
}
DisjSets:: find(int x)
{
if(s[x]<=0)
return x;
else
return find(s[x]);
}
13
Smart Union Algorithms

• Union-by-size: make the smaller tree a


subtree of the larger. If union-by-size, the
depth of any node is never more than
logN: a find operation is O(logN).
• Union-by-Height: make the shallow tree a
subtree of the deeper

14
Union-by-size : Example: union(4,5)
Union-by-height : Example: union(4,5)
Smart Union Algorithms
/* Union-by-height: */
void DisjSets::unionSets(root1, root2)
{
if(s[root2]<s[root1])
s[root1]=root2;
else
{
if(s[root1]==s[root2])
s[root1]--;
s[root2]=root1;
}
}
17
Path Compression for faster find
• Path compression for find(x): every node
on the path from x to the root has its
parent changed to the root: make the tree
shallow.
DisjSets:: find(int x)
{
if(s[x]<=0)
return x;
else
return s[x]=find(s[x]);
}
18

Vous aimerez peut-être aussi