SlideShare a Scribd company logo
Graphs
CS 308 – Data Structures
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
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)
Directed vs. undirected graphs
• When the edges in a graph have no
direction, the graph is called undirected
• 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 !!
• Trees are special cases of graphs!!
Trees vs graphs
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
• What is the number of edges in a complete
directed graph with N vertices?
N * (N-1)
Graph terminology (cont.)
2
( )
O N
• What is the number of edges in a complete
undirected graph with N vertices?
N * (N-1) / 2
Graph terminology (cont.)
2
( )
O N
• Weighted graph: a graph in which each edge
carries a value
Graph terminology (cont.)
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
Array-based implementation
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)
Linked-list implementation
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
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)
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)
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)
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];
}
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)
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
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.)
start end
(initialization)
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)
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)
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]);
}
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)
• 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"
start end
(initialization)
next:
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)
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;
}
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
• Common algorithms: Dijkstra's algorithm,
Bellman-Ford algorithm
• BFS can be used to solve the shortest graph
problem when the graph is weightless or all
the weights are the same
(mark vertices before Enqueue)
Single-source shortest-path problem
(cont.)
Exercises
• 24-37

More Related Content

Similar to Graphs.ppt

LEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdfLEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdf
MuhammadUmerIhtisham
 
Graphs
GraphsGraphs
Graphs
GraphsGraphs
lec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.pptlec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.ppt
TalhaFarooqui12
 
graph_theory_1-11.pdf___________________
graph_theory_1-11.pdf___________________graph_theory_1-11.pdf___________________
graph_theory_1-11.pdf___________________
ssuser1989da
 
Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]
Muhammad Hammad Waseem
 
Graph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptxGraph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptx
bashirabdullah789
 
Graphs
GraphsGraphs
Graphs
amudha arul
 
lecture 17
lecture 17lecture 17
lecture 17sajinsc
 
Graph Theory
Graph TheoryGraph Theory
Graph Theory
Rashmi Bhat
 
BRIEF RELETIONSHIP BETWEEN ADJACENCY MATRIX AND LIST.pptx
BRIEF RELETIONSHIP BETWEEN ADJACENCY MATRIX AND LIST.pptxBRIEF RELETIONSHIP BETWEEN ADJACENCY MATRIX AND LIST.pptx
BRIEF RELETIONSHIP BETWEEN ADJACENCY MATRIX AND LIST.pptx
CHIRANTANMONDAL2
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
Pooja Bhojwani
 
Graphs
GraphsGraphs
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdfClass01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf
ChristianKapsales1
 
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
Graph Analytics - From the Whiteboard to Your Toolbox - Sam LermaGraph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
PyData
 
18 Basic Graph Algorithms
18 Basic Graph Algorithms18 Basic Graph Algorithms
18 Basic Graph Algorithms
Andres Mendez-Vazquez
 
graph ASS (1).ppt
graph ASS (1).pptgraph ASS (1).ppt
graph ASS (1).ppt
ARVIND SARDAR
 
Graphs in data structures
Graphs in data structuresGraphs in data structures
Graphs in data structures
Savit Chandra
 
Graph ASS DBATU.pptx
Graph ASS DBATU.pptxGraph ASS DBATU.pptx
Graph ASS DBATU.pptx
ARVIND SARDAR
 

Similar to Graphs.ppt (20)

LEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdfLEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdf
 
Graphs
GraphsGraphs
Graphs
 
Graphs
GraphsGraphs
Graphs
 
lec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.pptlec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.ppt
 
graph_theory_1-11.pdf___________________
graph_theory_1-11.pdf___________________graph_theory_1-11.pdf___________________
graph_theory_1-11.pdf___________________
 
Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]
 
Graph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptxGraph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptx
 
Graphs
GraphsGraphs
Graphs
 
lecture 17
lecture 17lecture 17
lecture 17
 
Graph Theory
Graph TheoryGraph Theory
Graph Theory
 
BRIEF RELETIONSHIP BETWEEN ADJACENCY MATRIX AND LIST.pptx
BRIEF RELETIONSHIP BETWEEN ADJACENCY MATRIX AND LIST.pptxBRIEF RELETIONSHIP BETWEEN ADJACENCY MATRIX AND LIST.pptx
BRIEF RELETIONSHIP BETWEEN ADJACENCY MATRIX AND LIST.pptx
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
 
Graphs
GraphsGraphs
Graphs
 
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdfClass01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf
 
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
Graph Analytics - From the Whiteboard to Your Toolbox - Sam LermaGraph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
 
8150.graphs
8150.graphs8150.graphs
8150.graphs
 
18 Basic Graph Algorithms
18 Basic Graph Algorithms18 Basic Graph Algorithms
18 Basic Graph Algorithms
 
graph ASS (1).ppt
graph ASS (1).pptgraph ASS (1).ppt
graph ASS (1).ppt
 
Graphs in data structures
Graphs in data structuresGraphs in data structures
Graphs in data structures
 
Graph ASS DBATU.pptx
Graph ASS DBATU.pptxGraph ASS DBATU.pptx
Graph ASS DBATU.pptx
 

Recently uploaded

Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 

Recently uploaded (20)

Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 

Graphs.ppt

  • 1. Graphs CS 308 – Data Structures
  • 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
  • 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)
  • 4. Directed vs. undirected graphs • When the edges in a graph have no direction, the graph is called undirected
  • 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 !!
  • 6. • Trees are special cases of graphs!! Trees vs graphs
  • 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
  • 8. • What is the number of edges in a complete directed graph with N vertices? N * (N-1) Graph terminology (cont.) 2 ( ) O N
  • 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
  • 10. • Weighted graph: a graph in which each edge carries a value Graph terminology (cont.)
  • 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
  • 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)
  • 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
  • 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)
  • 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)
  • 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)
  • 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]; }
  • 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)
  • 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
  • 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.)
  • 24.
  • 25.
  • 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)
  • 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)
  • 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]); }
  • 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)
  • 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"
  • 32. next:
  • 33.
  • 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)
  • 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; }
  • 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
  • 37. • Common algorithms: Dijkstra's algorithm, Bellman-Ford algorithm • BFS can be used to solve the shortest graph problem when the graph is weightless or all the weights are the same (mark vertices before Enqueue) Single-source shortest-path problem (cont.)