SlideShare a Scribd company logo
Graphs
Data Structures
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
What is a graph?
• A data structure that consists of a set of nodes
(vertices) and a set of edges that relate the nodes
to each other
• The set of edges describes relationships among the
vertices
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Formal definition of graphs
• 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)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Directed vs. undirected graphs
• When the edges in a graph have no
direction, the graph is called undirected
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
• When the edges in a graph have a direction,
the graph is called directed (or digraph)
Directed vs. undirected graphs
(cont.)
E(Graph2) = {(1,3) (3,1) (5,9) (9,11)
(5,7)
Warning: if the graph is
directed, the order of the
vertices in each edge is
important !!
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
• Trees are special cases of graphs!!
Trees vs graphs
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Graph terminology
• Adjacent nodes: two nodes are adjacent if they are
connected by an edge
• Path: a sequence of vertices that connect two nodes in
a graph
• Complete graph: a graph in which every vertex is
directly connected to every other vertex
5 is adjacent to 7
7 is adjacent from 5
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
• What is the number of edges in a complete
directed graph with N vertices?
N * (N-1)
Graph terminology (cont.)
2
( )
O N
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
• What is the number of edges in a complete
undirected graph with N vertices?
N * (N-1) / 2
Graph terminology (cont.)
2
( )
O N
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
• Weighted graph: a graph in which each edge
carries a value
Graph terminology (cont.)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Graph implementation
• Array-based implementation
– A 1D array is used to represent the vertices
– A 2D array (adjacency matrix) is used to
represent the edges
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Array-based implementation
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Graph implementation (cont.)
• Linked-list implementation
– A 1D array is used to represent the vertices
– A list is used for each vertex v which contains the
vertices which are adjacent from v (adjacency list)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Linked-list implementation
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Adjacency matrix vs. adjacency list
representation
• Adjacency matrix
– Good for dense graphs --|E|~O(|V|2
)
– Memory requirements: O(|V| + |E|) = O(|V|2
)
– Connectivity between two vertices can be tested
quickly
• Adjacency list
– Good for sparse graphs -- |E|~O(|V|)
– Memory requirements: O(|V| + |E|)=O(|V|)
– Vertices adjacent to another vertex can be found
quickly Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Graph specification based on
adjacency matrix representation
const int NULL_EDGE = 0;
template<class VertexType>
class GraphType {
public:
GraphType(int);
~GraphType();
void MakeEmpty();
bool IsEmpty() const;
bool IsFull() const;
void AddVertex(VertexType);
void AddEdge(VertexType, VertexType, int);
int WeightIs(VertexType, VertexType);
void GetToVertices(VertexType, QueType<VertexType>&);
void ClearMarks();
void MarkVertex(VertexType);
bool IsMarked(VertexType) const;
private:
int numVertices;
int maxVertices;
VertexType* vertices;
int **edges;
bool* marks;
};
(continues)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
template<class VertexType>
GraphType<VertexType>::GraphType(int maxV)
{
numVertices = 0;
maxVertices = maxV;
vertices = new VertexType[maxV];
edges = new int[maxV];
for(int i = 0; i < maxV; i++)
edges[i] = new int[maxV];
marks = new bool[maxV];
}
template<class VertexType>
GraphType<VertexType>::~GraphType()
{
delete [] vertices;
for(int i = 0; i < maxVertices; i++)
delete [] edges[i];
delete [] edges;
delete [] marks;
}
(continues)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
void GraphType<VertexType>::AddVertex(VertexType vertex)
{
vertices[numVertices] = vertex;
for(int index = 0; index < numVertices; index++) {
edges[numVertices][index] = NULL_EDGE;
edges[index][numVertices] = NULL_EDGE;
}
numVertices++;
}
template<class VertexType>
void GraphType<VertexType>::AddEdge(VertexType fromVertex,
VertexType toVertex, int weight)
{
int row;
int column;
row = IndexIs(vertices, fromVertex);
col = IndexIs(vertices, toVertex);
edges[row][col] = weight;
}
(continues)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
template<class VertexType>
int GraphType<VertexType>::WeightIs(VertexType fromVertex,
VertexType toVertex)
{
int row;
int column;
row = IndexIs(vertices, fromVertex);
col = IndexIs(vertices, toVertex);
return edges[row][col];
}
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Graph searching
• Problem: find a path between two nodes of
the graph (e.g., Austin and Washington)
• Methods: Depth-First-Search (DFS) or
Breadth-First-Search (BFS)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
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
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Set found to false
stack.Push(startVertex)
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"
Depth-First-Search (DFS) (cont.)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
start end
(initialization)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
template <class ItemType>
void DepthFirstSearch(GraphType<VertexType> graph, VertexType
startVertex, VertexType endVertex)
{
StackType<VertexType> stack;
QueType<VertexType> vertexQ;
bool found = false;
VertexType vertex;
VertexType item;
graph.ClearMarks();
stack.Push(startVertex);
do {
stack.Pop(vertex);
if(vertex == endVertex)
found = true;
(continues)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
else {
if(!graph.IsMarked(vertex)) {
graph.MarkVertex(vertex);
graph.GetToVertices(vertex, vertexQ);
while(!vertexQ.IsEmpty()) {
vertexQ.Dequeue(item);
if(!graph.IsMarked(item))
stack.Push(item);
}
}
} while(!stack.IsEmpty() && !found);
if(!found)
cout << "Path not found" << endl;
}
(continues)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
template<class VertexType>
void GraphType<VertexType>::GetToVertices(VertexType vertex,
QueTye<VertexType>& adjvertexQ)
{
int fromIndex;
int toIndex;
fromIndex = IndexIs(vertices, vertex);
for(toIndex = 0; toIndex < numVertices; toIndex++)
if(edges[fromIndex][toIndex] != NULL_EDGE)
adjvertexQ.Enqueue(vertices[toIndex]);
}
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Breadth-First-Searching (BFS)
• What is the idea behind BFS?
– Look at all possible paths at the same depth
before you go at a deeper 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)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
• BFS can be implemented efficiently using a queue
Set found to false
queue.Enqueue(startVertex)
DO
queue.Dequeue(vertex)
IF vertex == endVertex
Set found to true
ELSE
Enqueue all adjacent vertices onto queue
WHILE !queue.IsEmpty() AND !found
• Should we mark a vertex when it is enqueued or
when it is dequeued ?
Breadth-First-Searching (BFS) (cont.)
IF(!found)
Write "Path does not exist"
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
start end
(initialization)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
next:
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
template<class VertexType>
void BreadthFirtsSearch(GraphType<VertexType> graph,
VertexType startVertex, VertexType endVertex);
{
QueType<VertexType> queue;
QueType<VertexType> vertexQ;//
bool found = false;
VertexType vertex;
VertexType item;
graph.ClearMarks();
queue.Enqueue(startVertex);
do {
queue.Dequeue(vertex);
if(vertex == endVertex)
found = true;
(continues)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
else {
if(!graph.IsMarked(vertex)) {
graph.MarkVertex(vertex);
graph.GetToVertices(vertex, vertexQ);
while(!vertxQ.IsEmpty()) {
vertexQ.Dequeue(item);
if(!graph.IsMarked(item))
queue.Enqueue(item);
}
}
}
} while (!queue.IsEmpty() && !found);
if(!found)
cout << "Path not found" << endl;
}
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Single-source shortest-path problem
• There are multiple paths from a source vertex
to a destination vertex
• Shortest path: the path whose total weight
(i.e., sum of edge weights) is minimum
• Examples:
– Austin->Houston->Atlanta->Washington:
1560 miles
– Austin->Dallas->Denver->Atlanta->Washington:
2980 miles
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
• Common algorithms: Dijkstra's algorithm,
Bellman-Ford algorithm
• BFS can be used to solve the shortest graph
problem when the graph is weightless
weightless or all
the weights are the same
(mark vertices before Enqueue)
Single-source shortest-path problem
(cont.)
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,
Exercises
• 24-37
Prepared By K.Vimala
M.Sc.,M.Phil.,MBA.,B.Ed.,

More Related Content

PPTX
Graph Data Structure
PPT
Graphs.ppt of mathemaics we have to clar all doubts
PPT
Graphs.ppt
PPTX
Data Structures and Agorithm: DS 21 Graph Theory.pptx
PPT
Graphs Presentation of University by Coordinator
PPTX
Data Structures - Lecture 10 [Graphs]
PDF
Graph Data Structure
PPT
Graphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.ppt
Graph Data Structure
Graphs.ppt of mathemaics we have to clar all doubts
Graphs.ppt
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Graphs Presentation of University by Coordinator
Data Structures - Lecture 10 [Graphs]
Graph Data Structure
Graphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.pptGraphs.ppt

Similar to Graphs concept in data structures and algorithms.ppt (20)

PPT
lec 09-graphs-bfs-dfs.ppt
PPT
Graphs (1)
PPT
Graphs
PPTX
UNIT III.pptx
PPTX
UNIT IV NON LINEAR DATA STRUCTURES - GRAPH
PPT
Chapter 23 aoa
PPTX
Graph data structures for ppt for understanding.pptx
PDF
LEC 12-DSALGO-GRAPHS(final12).pdf
PPTX
UNIT IV NON LINEAR DATA STRUCTURES - GRAPH.pptx
PPT
Unit VI - Graphs.ppt
PPT
Data structure computer graphs
PPT
14. GRAPH in data structures and algorithm.ppt
PPT
PPTX
DATA STRUCTURES.pptx
PPTX
Data Structure and algorithms - Graph1.pptx
PPT
Data Structures-Non Linear DataStructures-Graphs
PPTX
Unit 9 graph
lec 09-graphs-bfs-dfs.ppt
Graphs (1)
Graphs
UNIT III.pptx
UNIT IV NON LINEAR DATA STRUCTURES - GRAPH
Chapter 23 aoa
Graph data structures for ppt for understanding.pptx
LEC 12-DSALGO-GRAPHS(final12).pdf
UNIT IV NON LINEAR DATA STRUCTURES - GRAPH.pptx
Unit VI - Graphs.ppt
Data structure computer graphs
14. GRAPH in data structures and algorithm.ppt
DATA STRUCTURES.pptx
Data Structure and algorithms - Graph1.pptx
Data Structures-Non Linear DataStructures-Graphs
Unit 9 graph
Ad

More from vimalak8 (11)

PPTX
php various operators and its types.pptx
PPTX
data stricture concept graph coloring.pptx
PPTX
cloud computing ,types and working1.pptx
PPTX
artificial intellegence heuristic search.pptx
PPTX
fundamentals of python programmingg.pptx
PPTX
python programming control structures.pptx
PPT
open system interconnection and TCP/IPmodel.ppt
PPTX
introduction to computer networking.pptx
PPT
basics of computer networking and its introduction.ppt
PPTX
data science process in data analytics.pptx
PPTX
AVL Tree concept in data structures.pptx
php various operators and its types.pptx
data stricture concept graph coloring.pptx
cloud computing ,types and working1.pptx
artificial intellegence heuristic search.pptx
fundamentals of python programmingg.pptx
python programming control structures.pptx
open system interconnection and TCP/IPmodel.ppt
introduction to computer networking.pptx
basics of computer networking and its introduction.ppt
data science process in data analytics.pptx
AVL Tree concept in data structures.pptx
Ad

Recently uploaded (20)

DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Machine Learning_overview_presentation.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
A Presentation on Artificial Intelligence
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Big Data Technologies - Introduction.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPT
Teaching material agriculture food technology
The AUB Centre for AI in Media Proposal.docx
Advanced methodologies resolving dimensionality complications for autism neur...
Diabetes mellitus diagnosis method based random forest with bat algorithm
Machine Learning_overview_presentation.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
A Presentation on Artificial Intelligence
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
The Rise and Fall of 3GPP – Time for a Sabbatical?
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Programs and apps: productivity, graphics, security and other tools
Machine learning based COVID-19 study performance prediction
Big Data Technologies - Introduction.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Spectroscopy.pptx food analysis technology
A comparative analysis of optical character recognition models for extracting...
Dropbox Q2 2025 Financial Results & Investor Presentation
Per capita expenditure prediction using model stacking based on satellite ima...
Review of recent advances in non-invasive hemoglobin estimation
Teaching material agriculture food technology

Graphs concept in data structures and algorithms.ppt

  • 1. Graphs Data Structures Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 2. What is a graph? • A data structure that consists of a set of nodes (vertices) and a set of edges that relate the nodes to each other • The set of edges describes relationships among the vertices Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 3. Formal definition of graphs • 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) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 4. Directed vs. undirected graphs • When the edges in a graph have no direction, the graph is called undirected Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 5. • When the edges in a graph have a direction, the graph is called directed (or digraph) Directed vs. undirected graphs (cont.) E(Graph2) = {(1,3) (3,1) (5,9) (9,11) (5,7) Warning: if the graph is directed, the order of the vertices in each edge is important !! Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 6. • Trees are special cases of graphs!! Trees vs graphs Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 7. Graph terminology • Adjacent nodes: two nodes are adjacent if they are connected by an edge • Path: a sequence of vertices that connect two nodes in a graph • Complete graph: a graph in which every vertex is directly connected to every other vertex 5 is adjacent to 7 7 is adjacent from 5 Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 8. • What is the number of edges in a complete directed graph with N vertices? N * (N-1) Graph terminology (cont.) 2 ( ) O N Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 9. • What is the number of edges in a complete undirected graph with N vertices? N * (N-1) / 2 Graph terminology (cont.) 2 ( ) O N Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 10. • Weighted graph: a graph in which each edge carries a value Graph terminology (cont.) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 11. Graph implementation • Array-based implementation – A 1D array is used to represent the vertices – A 2D array (adjacency matrix) is used to represent the edges Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 12. Array-based implementation Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 13. Graph implementation (cont.) • Linked-list implementation – A 1D array is used to represent the vertices – A list is used for each vertex v which contains the vertices which are adjacent from v (adjacency list) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 14. Linked-list implementation Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 15. Adjacency matrix vs. adjacency list representation • Adjacency matrix – Good for dense graphs --|E|~O(|V|2 ) – Memory requirements: O(|V| + |E|) = O(|V|2 ) – Connectivity between two vertices can be tested quickly • Adjacency list – Good for sparse graphs -- |E|~O(|V|) – Memory requirements: O(|V| + |E|)=O(|V|) – Vertices adjacent to another vertex can be found quickly Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 16. Graph specification based on adjacency matrix representation const int NULL_EDGE = 0; template<class VertexType> class GraphType { public: GraphType(int); ~GraphType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; void AddVertex(VertexType); void AddEdge(VertexType, VertexType, int); int WeightIs(VertexType, VertexType); void GetToVertices(VertexType, QueType<VertexType>&); void ClearMarks(); void MarkVertex(VertexType); bool IsMarked(VertexType) const; private: int numVertices; int maxVertices; VertexType* vertices; int **edges; bool* marks; }; (continues) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 17. template<class VertexType> GraphType<VertexType>::GraphType(int maxV) { numVertices = 0; maxVertices = maxV; vertices = new VertexType[maxV]; edges = new int[maxV]; for(int i = 0; i < maxV; i++) edges[i] = new int[maxV]; marks = new bool[maxV]; } template<class VertexType> GraphType<VertexType>::~GraphType() { delete [] vertices; for(int i = 0; i < maxVertices; i++) delete [] edges[i]; delete [] edges; delete [] marks; } (continues) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 18. void GraphType<VertexType>::AddVertex(VertexType vertex) { vertices[numVertices] = vertex; for(int index = 0; index < numVertices; index++) { edges[numVertices][index] = NULL_EDGE; edges[index][numVertices] = NULL_EDGE; } numVertices++; } template<class VertexType> void GraphType<VertexType>::AddEdge(VertexType fromVertex, VertexType toVertex, int weight) { int row; int column; row = IndexIs(vertices, fromVertex); col = IndexIs(vertices, toVertex); edges[row][col] = weight; } (continues) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 19. template<class VertexType> int GraphType<VertexType>::WeightIs(VertexType fromVertex, VertexType toVertex) { int row; int column; row = IndexIs(vertices, fromVertex); col = IndexIs(vertices, toVertex); return edges[row][col]; } Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 20. Graph searching • Problem: find a path between two nodes of the graph (e.g., Austin and Washington) • Methods: Depth-First-Search (DFS) or Breadth-First-Search (BFS) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 21. 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 Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 22. Set found to false stack.Push(startVertex) 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" Depth-First-Search (DFS) (cont.) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 23. start end (initialization) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 26. template <class ItemType> void DepthFirstSearch(GraphType<VertexType> graph, VertexType startVertex, VertexType endVertex) { StackType<VertexType> stack; QueType<VertexType> vertexQ; bool found = false; VertexType vertex; VertexType item; graph.ClearMarks(); stack.Push(startVertex); do { stack.Pop(vertex); if(vertex == endVertex) found = true; (continues) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 27. else { if(!graph.IsMarked(vertex)) { graph.MarkVertex(vertex); graph.GetToVertices(vertex, vertexQ); while(!vertexQ.IsEmpty()) { vertexQ.Dequeue(item); if(!graph.IsMarked(item)) stack.Push(item); } } } while(!stack.IsEmpty() && !found); if(!found) cout << "Path not found" << endl; } (continues) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 28. template<class VertexType> void GraphType<VertexType>::GetToVertices(VertexType vertex, QueTye<VertexType>& adjvertexQ) { int fromIndex; int toIndex; fromIndex = IndexIs(vertices, vertex); for(toIndex = 0; toIndex < numVertices; toIndex++) if(edges[fromIndex][toIndex] != NULL_EDGE) adjvertexQ.Enqueue(vertices[toIndex]); } Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 29. Breadth-First-Searching (BFS) • What is the idea behind BFS? – Look at all possible paths at the same depth before you go at a deeper 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) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 30. • BFS can be implemented efficiently using a queue Set found to false queue.Enqueue(startVertex) DO queue.Dequeue(vertex) IF vertex == endVertex Set found to true ELSE Enqueue all adjacent vertices onto queue WHILE !queue.IsEmpty() AND !found • Should we mark a vertex when it is enqueued or when it is dequeued ? Breadth-First-Searching (BFS) (cont.) IF(!found) Write "Path does not exist" Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 31. start end (initialization) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 34. template<class VertexType> void BreadthFirtsSearch(GraphType<VertexType> graph, VertexType startVertex, VertexType endVertex); { QueType<VertexType> queue; QueType<VertexType> vertexQ;// bool found = false; VertexType vertex; VertexType item; graph.ClearMarks(); queue.Enqueue(startVertex); do { queue.Dequeue(vertex); if(vertex == endVertex) found = true; (continues) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 35. else { if(!graph.IsMarked(vertex)) { graph.MarkVertex(vertex); graph.GetToVertices(vertex, vertexQ); while(!vertxQ.IsEmpty()) { vertexQ.Dequeue(item); if(!graph.IsMarked(item)) queue.Enqueue(item); } } } } while (!queue.IsEmpty() && !found); if(!found) cout << "Path not found" << endl; } Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 36. Single-source shortest-path problem • There are multiple paths from a source vertex to a destination vertex • Shortest path: the path whose total weight (i.e., sum of edge weights) is minimum • Examples: – Austin->Houston->Atlanta->Washington: 1560 miles – Austin->Dallas->Denver->Atlanta->Washington: 2980 miles Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 37. • Common algorithms: Dijkstra's algorithm, Bellman-Ford algorithm • BFS can be used to solve the shortest graph problem when the graph is weightless weightless or all the weights are the same (mark vertices before Enqueue) Single-source shortest-path problem (cont.) Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,
  • 38. Exercises • 24-37 Prepared By K.Vimala M.Sc.,M.Phil.,MBA.,B.Ed.,