SlideShare a Scribd company logo
1 of 35
Download to read offline
Graph-theoretic Models,
Lecture 3, Segment 1
John Guttag
MIT Department of Electrical Engineering and
Computer Science
6.00.2X LECTURE 3 1
Programs that help us understand the world and solve
practical problems
Saw how we could map the informal problem of
choosing what to eat into an optimization problem,
and how we could design a program to solve it
Now want to look at class of models called graphs
Computational Models
6.00.2X LECTURE 3 2
Set of nodes (vertices)
◦ Might have properties associated with them
Set of edges (arcs) each consisting of a pair of nodes
◦ Undirected (graph)
◦ Directed (digraph)
◦ Source (parent) and destination (child) nodes
◦ Unweighted or weighted
What’s a Graph?
6.00.2X LECTURE 3 3
Set of nodes (vertices)
◦ Might have properties associated with them
Set of edges (arcs) each consisting of a pair of nodes
◦ Undirected (graph)
◦ Directed (digraph)
◦ Source (parent) and destination (child) nodes
◦ Unweighted or weighted
What’s a Graph?
6.00.2X LECTURE 3 4
10
12
3
To capture useful relationships among entities
◦ Rail links between Paris and London
◦ How the atoms in a molecule related to one another
◦ Ancestral relationships
Why Graphs?
6.00.2X LECTURE 3 5
A directed graph in which each pair of nodes is
connected by a single path
◦ Recall the search trees we used to solve knapsack
problem
Trees: An Important Special Case
6.00.2X LECTURE 3 6
World is full of networks based on relationships
◦ Computer networks
◦ Transportation networks
◦ Financial networks
◦ Sewer networks
◦ Political networks
◦ Criminal networks
◦ Social networks
◦ Etc.
Why Graphs Are So Useful
6.00.2X LECTURE 3 7
mapr.com
Graph Theory Saves Me Time Every Day
6.00.2X LECTURE 3 8
www.google.com
Model road system using a digraph
◦ Nodes: points where roads end or meet
◦ Edges: connections between points
◦ Each edge has a weight indicating time it will take to get
from source node to destination node for that edge
Solve a graph optimization problem
◦ Shortest weighted path between my house and my office
Getting John to the Office
6.00.2X LECTURE 3 9
CC-BY SusanLesch
First Reported Use of Graph Theory
6.00.2X LECTURE 3 10
Bridges of
Königsberg
(1735)
Possible to take
a walk that
traverses each of
the 7 bridges
exactly once?
Leonhard Euler’s Model
6.00.2X LECTURE 3 11
Each island a node
Each bridge an undirected edge
Model abstracts away irrelevant details
◦ Size of islands
◦ Length of bridges
Is there a path that contains each edge exactly once?
Implementing graphs
Some classic graph optimization problems
Next Segment
6.00.2X LECTURE 3 12
CC-BY Juliaytsai94
Graph-theoretic Models,
Lecture 3, Segment 2
John Guttag
MIT Department of Electrical Engineering and
Computer Science
6.00.2X LECTURE 3 1
Class Node
6.00.2X LECTURE 3 2
class Node(object):
def __init__(self, name):
"""Assumes name is a string"""
self.name = name
def getName(self):
return self.name
def __str__(self):
return self.name
Class Edge
6.00.2X LECTURE 3 3
class Edge(object):
def __init__(self, src, dest):
"""Assumes src and dest are nodes"""
self.src = src
self.dest = dest
def getSource(self):
return self.src
def getDestination(self):
return self.dest
def __str__(self):
return self.src.getName() + '->’
+ self.dest.getName()
Adjacency matrix
◦ Rows: source nodes
◦ Columns: destination nodes
◦ Cell[s, d] = 1 if there is an edge from s to d
0 otherwise
Adjacency list
◦ Associate with each node a list of destination nodes
Common Representations of Digraphs
6.00.2X LECTURE 3 4
Class Digraph, part 1
6.00.2X LECTURE 3 5
class Digraph(object):
"""edges is a dict mapping each node to a list of
its children""”
def __init__(self):
self.edges = {}
def addNode(self, node):
if node in self.edges:
raise ValueError('Duplicate node')
else:
self.edges[node] = []
def addEdge(self, edge):
src = edge.getSource()
dest = edge.getDestination()
if not (src in self.edges and dest in self.edges):
raise ValueError('Node not in graph')
self.edges[src].append(dest)
Class Digraph, part 2
6.00.2X LECTURE 3 6
def childrenOf(self, node):
return self.edges[node]
def hasNode(self, node):
return node in self.edges
def getNode(self, name):
for n in self.edges:
if n.getName() == name:
return n
raise NameError(name)
def __str__(self):
result = ''
for src in self.edges:
for dest in self.edges[src]:
result = result + src.getName() + '->'
+ dest.getName() + 'n'
return result[:-1] #omit final newline
Why is Graph a subclass of digraph?
Remember the substitution rule from 6.00.1x?
◦ If client code works correctly using an instance of the
supertype, it should also work correctly when an instance
of the subtype is substituted for the instance of the
supertype
Any program that works with a Digraph will also work
with a Graph (but not vice versa)
Class Graph
6.00.2X LECTURE 3 7
class Graph(Digraph):
def addEdge(self, edge):
Digraph.addEdge(self, edge)
rev = Edge(edge.getDestination(), edge.getSource())
Digraph.addEdge(self, rev)
Shortest path from n1 to n2
◦ Shortest sequence of edges such that
◦ Source node of first edge is n1
◦ Destination of last edge is n2
◦ For edges, e1 and e2, in the sequence, if e2 follows e1 in the
sequence, the source of e2 is the destination of e1
Shortest weighted path
◦ Minimize the sum of the weights of the edges in the path
A Classic Graph Optimization Problem
6.00.2X LECTURE 3 8
Finding a route from one city to another
Designing communication networks
Finding a path for a molecule through a chemical
labyrinth
…
Some Shortest Path Problems
6.00.2X LECTURE 3 9
CC-BY Juliaytsai94
www.google.com
An Example
6.00.2X LECTURE 3 10
Boston
Providence New York
Chicago Denver
Phoenix
Los Angeles
Adjacency List
Boston: Providence, New York
Providence: Boston, New York
New York: Chicago
Chicago: Denver, Phoenix
Denver: Phoenix, New York
Los Angeles: Boston
Build the Graph
6.00.2X LECTURE 3 11
def buildCityGraph():
g = Digraph()
for name in ('Boston', 'Providence', 'New York', 'Chicago',
'Denver', 'Phoenix', 'Los Angeles'): #Create 7 nodes
g.addNode(Node(name))
g.addEdge(Edge(g.getNode('Boston'), g.getNode('Providence')))
g.addEdge(Edge(g.getNode('Boston'), g.getNode('New York')))
g.addEdge(Edge(g.getNode('Providence'), g.getNode('Boston')))
g.addEdge(Edge(g.getNode('Providence'), g.getNode('New York')))
g.addEdge(Edge(g.getNode('New York'), g.getNode('Chicago')))
g.addEdge(Edge(g.getNode('Chicago'), g.getNode('Denver')))
g.addEdge(Edge(g.getNode('Denver'), g.getNode('Phoenix')))
g.addEdge(Edge(g.getNode('Denver'), g.getNode(’New York')))
g.addEdge(Edge(g.getNode('Chicago'), g.getNode('Phoenix')))
g.addEdge(Edge(g.getNode('Los Angeles'), g.getNode('Boston')))
Solutions to shortest path problem
Coming Up
6.00.2X LECTURE 3 12
Graph-theoretic Models,
Lecture 3, Segment 3
John Guttag
MIT Department of Electrical Engineering and
Computer Science
6.00.2X LECTURE 3 1
Algorithm 1, depth-first search (DFS)
Similar to left-first depth-first method of enumerating
a search tree (Lecture 2)
Main difference is that graph might have cycles, so we
must keep track of what nodes we have visited
Finding the Shortest Path
6.00.2X LECTURE 3 2
Depth First Search (DFS)
6.00.2X LECTURE 3 3
def DFS(graph, start, end, path, shortest):
path = path + [start]
if start == end:
return path
for node in graph.childrenOf(start):
if node not in path: #avoid cycles
if shortest == None or len(path) < len(shortest):
newPath = DFS(graph, node, end, path,
shortest, toPrint)
if newPath != None:
shortest = newPath
return shortest
def shortestPath(graph, start, end):
return DFS(graph, start, end, [], None, toPrint)
DFS called from a
wrapper function:
shortestPath
Gets recursion started properly
Provides appropriate abstraction
Test DFS
6.00.2X LECTURE 3 4
def testSP(source, destination):
g = buildGraph()
sp = shortestPath(g, g.getNode(source), g.getNode(destination)
if sp != None:
print('Shortest path from', source, 'to',
destination, 'is', printPath(sp))
else:
print('There is no path from', source, 'to', destination)
testSP('Boston', ’Chicago')
An Example
6.00.2X LECTURE 3 5
Boston
Providence New York
Chicago Denver
Phoenix
Los Angeles
Adjacency List
Boston: Providence, New York
Providence: Boston, New York
New York: Chicago
Chicago: Denver, Phoenix
Denver: Phoenix, New York
Los Angeles: Boston
Current DFS path: Chicago
Current DFS path: Chicago->Denver
Current DFS path: Chicago->Denver->Phoenix
Current DFS path: Chicago->Denver->New York
Already visited Chicago
There is no path from Chicago to Boston
Output (Chicago to Boston)
6.00.2X LECTURE 3 6
Boston
Providence New York
Chicago Denver
Phoenix
Los Angeles
Current DFS path: Boston
Current DFS path: Boston->Providence
Already visited Boston
Current DFS path: Boston->Providence->New York
Current DFS path: Boston->Providence->New York->Chicago
Current DFS path: Boston->Providence->New York->Chicago->Denver
Current DFS path: Boston->Providence->New York->Chicago->Denver->Phoenix Found path
Already visited New York
Current DFS path: Boston->New York
Current DFS path: Boston->New York->Chicago
Current DFS path: Boston->New York->Chicago->Denver
Current DFS path: Boston->New York->Chicago->Denver->Phoenix Found a shorter path
Already visited New York
Shortest path from Boston to Phoenix is Boston->New York->Chicago->Denver->Phoenix
Output (Boston to Phoenix)
6.00.2X LECTURE 3 7
Algorithm 2: Breadth-first Search (BFS)
6.00.2X LECTURE 3 8
def BFS(graph, start, end, toPrint = False):
initPath = [start]
pathQueue = [initPath]
if toPrint:
print('Current BFS path:', printPath(pathQueue))
while len(pathQueue) != 0:
#Get and remove oldest element in pathQueue
tmpPath = pathQueue.pop(0)
print('Current BFS path:', printPath(tmpPath))
lastNode = tmpPath[-1]
if lastNode == end:
return tmpPath
for nextNode in graph.childrenOf(lastNode):
if nextNode not in tmpPath:
newPath = tmpPath + [nextNode]
pathQueue.append(newPath)
return None
?
Explore all paths with n hops before
exploring any path with more than n hops
Want to minimize the sum of the weights of the edges,
not the number of edges
DFS can be easily modified to do this
BFS cannot, since shortest weighted path may have
more than the minimum number of hops
What About a Weighted Shortest Path
6.00.2X LECTURE 3 9
Graphs are cool
◦ Best way to create a model of many things
◦ Capture relationships among objects
◦ Many important problems can be posed as graph
optimization problems we already know how to solve
Depth-first and breadth-first search are important
algorithms
◦ Can be used to solve many problems
Recap
6.00.2X LECTURE 3 10
Modeling situations with unpredictable events
Will make heavy use of plotting
◦ Lecture 4 is about plotting in Python
◦ Identical to a lecture in 6.00.1x, feel free to skip it if you
took 6.00.1x
Coming Up
6.00.2X LECTURE 3 11

More Related Content

Similar to Lecture 3.pdf

Everything is composable
Everything is composableEverything is composable
Everything is composableVictor Igor
 
Kmr slides
Kmr slidesKmr slides
Kmr slidesMeena124
 
PostgreSQL: Advanced features in practice
PostgreSQL: Advanced features in practicePostgreSQL: Advanced features in practice
PostgreSQL: Advanced features in practiceJano Suchal
 
GSP 125 RANK Education for Service--gsp125rank.com
GSP 125 RANK  Education for Service--gsp125rank.comGSP 125 RANK  Education for Service--gsp125rank.com
GSP 125 RANK Education for Service--gsp125rank.comclaric25
 
GraphFrames: Graph Queries In Spark SQL
GraphFrames: Graph Queries In Spark SQLGraphFrames: Graph Queries In Spark SQL
GraphFrames: Graph Queries In Spark SQLSpark Summit
 
GraphX: Graph Analytics in Apache Spark (AMPCamp 5, 2014-11-20)
GraphX: Graph Analytics in Apache Spark (AMPCamp 5, 2014-11-20)GraphX: Graph Analytics in Apache Spark (AMPCamp 5, 2014-11-20)
GraphX: Graph Analytics in Apache Spark (AMPCamp 5, 2014-11-20)Ankur Dave
 
GSP 125 Perfect Education/newtonhelp.com
GSP 125 Perfect Education/newtonhelp.comGSP 125 Perfect Education/newtonhelp.com
GSP 125 Perfect Education/newtonhelp.combellflower169
 
Gsp 125 Future Our Mission/newtonhelp.com
Gsp 125 Future Our Mission/newtonhelp.comGsp 125 Future Our Mission/newtonhelp.com
Gsp 125 Future Our Mission/newtonhelp.comamaranthbeg8
 
GSP 125 Become Exceptional/newtonhelp.com
GSP 125 Become Exceptional/newtonhelp.comGSP 125 Become Exceptional/newtonhelp.com
GSP 125 Become Exceptional/newtonhelp.combellflower148
 
GSP 125 Doing by learn/newtonhelp.com
GSP 125 Doing by learn/newtonhelp.comGSP 125 Doing by learn/newtonhelp.com
GSP 125 Doing by learn/newtonhelp.combellflower126
 
GSP 125 Enhance teaching/tutorialrank.com
 GSP 125 Enhance teaching/tutorialrank.com GSP 125 Enhance teaching/tutorialrank.com
GSP 125 Enhance teaching/tutorialrank.comjonhson300
 
GSP 125 Effective Communication/tutorialrank.com
 GSP 125 Effective Communication/tutorialrank.com GSP 125 Effective Communication/tutorialrank.com
GSP 125 Effective Communication/tutorialrank.comjonhson282
 
Lokesh 's Ip project Pokemon information
Lokesh 's Ip project Pokemon informationLokesh 's Ip project Pokemon information
Lokesh 's Ip project Pokemon informationbholu803201
 
D3.JS Tips & Tricks (export to svg, crossfilter, maps etc.)
D3.JS Tips & Tricks (export to svg, crossfilter, maps etc.)D3.JS Tips & Tricks (export to svg, crossfilter, maps etc.)
D3.JS Tips & Tricks (export to svg, crossfilter, maps etc.)Oleksii Prohonnyi
 
Ddp Cs3.0 Solar System
Ddp Cs3.0 Solar SystemDdp Cs3.0 Solar System
Ddp Cs3.0 Solar Systemboonzaai
 
Gsp 125 Education Organization -- snaptutorial.com
Gsp 125   Education Organization -- snaptutorial.comGsp 125   Education Organization -- snaptutorial.com
Gsp 125 Education Organization -- snaptutorial.comDavisMurphyB85
 
GSP 125 Technology levels--snaptutorial.com
GSP 125 Technology levels--snaptutorial.comGSP 125 Technology levels--snaptutorial.com
GSP 125 Technology levels--snaptutorial.comsholingarjosh136
 
Gsp 125 Massive Success / snaptutorial.com
Gsp 125  Massive Success / snaptutorial.comGsp 125  Massive Success / snaptutorial.com
Gsp 125 Massive Success / snaptutorial.comNorrisMistryzo
 

Similar to Lecture 3.pdf (20)

Everything is composable
Everything is composableEverything is composable
Everything is composable
 
Kmr slides
Kmr slidesKmr slides
Kmr slides
 
PostgreSQL: Advanced features in practice
PostgreSQL: Advanced features in practicePostgreSQL: Advanced features in practice
PostgreSQL: Advanced features in practice
 
Interactive High-Dimensional Visualization of Social Graphs
Interactive High-Dimensional Visualization of Social GraphsInteractive High-Dimensional Visualization of Social Graphs
Interactive High-Dimensional Visualization of Social Graphs
 
GSP 125 RANK Education for Service--gsp125rank.com
GSP 125 RANK  Education for Service--gsp125rank.comGSP 125 RANK  Education for Service--gsp125rank.com
GSP 125 RANK Education for Service--gsp125rank.com
 
GraphFrames: Graph Queries In Spark SQL
GraphFrames: Graph Queries In Spark SQLGraphFrames: Graph Queries In Spark SQL
GraphFrames: Graph Queries In Spark SQL
 
GraphX: Graph Analytics in Apache Spark (AMPCamp 5, 2014-11-20)
GraphX: Graph Analytics in Apache Spark (AMPCamp 5, 2014-11-20)GraphX: Graph Analytics in Apache Spark (AMPCamp 5, 2014-11-20)
GraphX: Graph Analytics in Apache Spark (AMPCamp 5, 2014-11-20)
 
GSP 125 Perfect Education/newtonhelp.com
GSP 125 Perfect Education/newtonhelp.comGSP 125 Perfect Education/newtonhelp.com
GSP 125 Perfect Education/newtonhelp.com
 
Gsp 125 Future Our Mission/newtonhelp.com
Gsp 125 Future Our Mission/newtonhelp.comGsp 125 Future Our Mission/newtonhelp.com
Gsp 125 Future Our Mission/newtonhelp.com
 
GSP 125 Become Exceptional/newtonhelp.com
GSP 125 Become Exceptional/newtonhelp.comGSP 125 Become Exceptional/newtonhelp.com
GSP 125 Become Exceptional/newtonhelp.com
 
GSP 125 Doing by learn/newtonhelp.com
GSP 125 Doing by learn/newtonhelp.comGSP 125 Doing by learn/newtonhelp.com
GSP 125 Doing by learn/newtonhelp.com
 
Computational Assignment Help
Computational Assignment HelpComputational Assignment Help
Computational Assignment Help
 
GSP 125 Enhance teaching/tutorialrank.com
 GSP 125 Enhance teaching/tutorialrank.com GSP 125 Enhance teaching/tutorialrank.com
GSP 125 Enhance teaching/tutorialrank.com
 
GSP 125 Effective Communication/tutorialrank.com
 GSP 125 Effective Communication/tutorialrank.com GSP 125 Effective Communication/tutorialrank.com
GSP 125 Effective Communication/tutorialrank.com
 
Lokesh 's Ip project Pokemon information
Lokesh 's Ip project Pokemon informationLokesh 's Ip project Pokemon information
Lokesh 's Ip project Pokemon information
 
D3.JS Tips & Tricks (export to svg, crossfilter, maps etc.)
D3.JS Tips & Tricks (export to svg, crossfilter, maps etc.)D3.JS Tips & Tricks (export to svg, crossfilter, maps etc.)
D3.JS Tips & Tricks (export to svg, crossfilter, maps etc.)
 
Ddp Cs3.0 Solar System
Ddp Cs3.0 Solar SystemDdp Cs3.0 Solar System
Ddp Cs3.0 Solar System
 
Gsp 125 Education Organization -- snaptutorial.com
Gsp 125   Education Organization -- snaptutorial.comGsp 125   Education Organization -- snaptutorial.com
Gsp 125 Education Organization -- snaptutorial.com
 
GSP 125 Technology levels--snaptutorial.com
GSP 125 Technology levels--snaptutorial.comGSP 125 Technology levels--snaptutorial.com
GSP 125 Technology levels--snaptutorial.com
 
Gsp 125 Massive Success / snaptutorial.com
Gsp 125  Massive Success / snaptutorial.comGsp 125  Massive Success / snaptutorial.com
Gsp 125 Massive Success / snaptutorial.com
 

Recently uploaded

Abortion Clinic in Kempton Park +27791653574 WhatsApp Abortion Clinic Service...
Abortion Clinic in Kempton Park +27791653574 WhatsApp Abortion Clinic Service...Abortion Clinic in Kempton Park +27791653574 WhatsApp Abortion Clinic Service...
Abortion Clinic in Kempton Park +27791653574 WhatsApp Abortion Clinic Service...mikehavy0
 
如何办理澳洲拉筹伯大学毕业证(LaTrobe毕业证书)成绩单原件一模一样
如何办理澳洲拉筹伯大学毕业证(LaTrobe毕业证书)成绩单原件一模一样如何办理澳洲拉筹伯大学毕业证(LaTrobe毕业证书)成绩单原件一模一样
如何办理澳洲拉筹伯大学毕业证(LaTrobe毕业证书)成绩单原件一模一样wsppdmt
 
Harnessing the Power of GenAI for BI and Reporting.pptx
Harnessing the Power of GenAI for BI and Reporting.pptxHarnessing the Power of GenAI for BI and Reporting.pptx
Harnessing the Power of GenAI for BI and Reporting.pptxParas Gupta
 
obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...
obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...
obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...yulianti213969
 
Northern New England Tableau User Group (TUG) May 2024
Northern New England Tableau User Group (TUG) May 2024Northern New England Tableau User Group (TUG) May 2024
Northern New England Tableau User Group (TUG) May 2024patrickdtherriault
 
jll-asia-pacific-capital-tracker-1q24.pdf
jll-asia-pacific-capital-tracker-1q24.pdfjll-asia-pacific-capital-tracker-1q24.pdf
jll-asia-pacific-capital-tracker-1q24.pdfjaytendertech
 
👉 Tirunelveli Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Gir...
👉 Tirunelveli Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Gir...👉 Tirunelveli Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Gir...
👉 Tirunelveli Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Gir...vershagrag
 
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...Elaine Werffeli
 
Ranking and Scoring Exercises for Research
Ranking and Scoring Exercises for ResearchRanking and Scoring Exercises for Research
Ranking and Scoring Exercises for ResearchRajesh Mondal
 
Introduction to Statistics Presentation.pptx
Introduction to Statistics Presentation.pptxIntroduction to Statistics Presentation.pptx
Introduction to Statistics Presentation.pptxAniqa Zai
 
Bios of leading Astrologers & Researchers
Bios of leading Astrologers & ResearchersBios of leading Astrologers & Researchers
Bios of leading Astrologers & Researchersdarmandersingh4580
 
Displacement, Velocity, Acceleration, and Second Derivatives
Displacement, Velocity, Acceleration, and Second DerivativesDisplacement, Velocity, Acceleration, and Second Derivatives
Displacement, Velocity, Acceleration, and Second Derivatives23050636
 
ℂall Girls In Navi Mumbai Hire Me Neha 9910780858 Top Class ℂall Girl Serviℂe...
ℂall Girls In Navi Mumbai Hire Me Neha 9910780858 Top Class ℂall Girl Serviℂe...ℂall Girls In Navi Mumbai Hire Me Neha 9910780858 Top Class ℂall Girl Serviℂe...
ℂall Girls In Navi Mumbai Hire Me Neha 9910780858 Top Class ℂall Girl Serviℂe...Amara arora$V15
 
DBMS UNIT 5 46 CONTAINS NOTES FOR THE STUDENTS
DBMS UNIT 5 46 CONTAINS NOTES FOR THE STUDENTSDBMS UNIT 5 46 CONTAINS NOTES FOR THE STUDENTS
DBMS UNIT 5 46 CONTAINS NOTES FOR THE STUDENTSSnehalVinod
 
Reconciling Conflicting Data Curation Actions: Transparency Through Argument...
Reconciling Conflicting Data Curation Actions:  Transparency Through Argument...Reconciling Conflicting Data Curation Actions:  Transparency Through Argument...
Reconciling Conflicting Data Curation Actions: Transparency Through Argument...Bertram Ludäscher
 
一比一原版(曼大毕业证书)曼尼托巴大学毕业证成绩单留信学历认证一手价格
一比一原版(曼大毕业证书)曼尼托巴大学毕业证成绩单留信学历认证一手价格一比一原版(曼大毕业证书)曼尼托巴大学毕业证成绩单留信学历认证一手价格
一比一原版(曼大毕业证书)曼尼托巴大学毕业证成绩单留信学历认证一手价格q6pzkpark
 
Case Study 4 Where the cry of rebellion happen?
Case Study 4 Where the cry of rebellion happen?Case Study 4 Where the cry of rebellion happen?
Case Study 4 Where the cry of rebellion happen?RemarkSemacio
 

Recently uploaded (20)

Abortion pills in Riyadh Saudi Arabia (+966572737505 buy cytotec
Abortion pills in Riyadh Saudi Arabia (+966572737505 buy cytotecAbortion pills in Riyadh Saudi Arabia (+966572737505 buy cytotec
Abortion pills in Riyadh Saudi Arabia (+966572737505 buy cytotec
 
Abortion Clinic in Kempton Park +27791653574 WhatsApp Abortion Clinic Service...
Abortion Clinic in Kempton Park +27791653574 WhatsApp Abortion Clinic Service...Abortion Clinic in Kempton Park +27791653574 WhatsApp Abortion Clinic Service...
Abortion Clinic in Kempton Park +27791653574 WhatsApp Abortion Clinic Service...
 
如何办理澳洲拉筹伯大学毕业证(LaTrobe毕业证书)成绩单原件一模一样
如何办理澳洲拉筹伯大学毕业证(LaTrobe毕业证书)成绩单原件一模一样如何办理澳洲拉筹伯大学毕业证(LaTrobe毕业证书)成绩单原件一模一样
如何办理澳洲拉筹伯大学毕业证(LaTrobe毕业证书)成绩单原件一模一样
 
Abortion pills in Jeddah | +966572737505 | Get Cytotec
Abortion pills in Jeddah | +966572737505 | Get CytotecAbortion pills in Jeddah | +966572737505 | Get Cytotec
Abortion pills in Jeddah | +966572737505 | Get Cytotec
 
Harnessing the Power of GenAI for BI and Reporting.pptx
Harnessing the Power of GenAI for BI and Reporting.pptxHarnessing the Power of GenAI for BI and Reporting.pptx
Harnessing the Power of GenAI for BI and Reporting.pptx
 
obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...
obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...
obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...
 
Northern New England Tableau User Group (TUG) May 2024
Northern New England Tableau User Group (TUG) May 2024Northern New England Tableau User Group (TUG) May 2024
Northern New England Tableau User Group (TUG) May 2024
 
jll-asia-pacific-capital-tracker-1q24.pdf
jll-asia-pacific-capital-tracker-1q24.pdfjll-asia-pacific-capital-tracker-1q24.pdf
jll-asia-pacific-capital-tracker-1q24.pdf
 
👉 Tirunelveli Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Gir...
👉 Tirunelveli Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Gir...👉 Tirunelveli Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Gir...
👉 Tirunelveli Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Gir...
 
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
 
Ranking and Scoring Exercises for Research
Ranking and Scoring Exercises for ResearchRanking and Scoring Exercises for Research
Ranking and Scoring Exercises for Research
 
Introduction to Statistics Presentation.pptx
Introduction to Statistics Presentation.pptxIntroduction to Statistics Presentation.pptx
Introduction to Statistics Presentation.pptx
 
Bios of leading Astrologers & Researchers
Bios of leading Astrologers & ResearchersBios of leading Astrologers & Researchers
Bios of leading Astrologers & Researchers
 
Displacement, Velocity, Acceleration, and Second Derivatives
Displacement, Velocity, Acceleration, and Second DerivativesDisplacement, Velocity, Acceleration, and Second Derivatives
Displacement, Velocity, Acceleration, and Second Derivatives
 
ℂall Girls In Navi Mumbai Hire Me Neha 9910780858 Top Class ℂall Girl Serviℂe...
ℂall Girls In Navi Mumbai Hire Me Neha 9910780858 Top Class ℂall Girl Serviℂe...ℂall Girls In Navi Mumbai Hire Me Neha 9910780858 Top Class ℂall Girl Serviℂe...
ℂall Girls In Navi Mumbai Hire Me Neha 9910780858 Top Class ℂall Girl Serviℂe...
 
DBMS UNIT 5 46 CONTAINS NOTES FOR THE STUDENTS
DBMS UNIT 5 46 CONTAINS NOTES FOR THE STUDENTSDBMS UNIT 5 46 CONTAINS NOTES FOR THE STUDENTS
DBMS UNIT 5 46 CONTAINS NOTES FOR THE STUDENTS
 
Reconciling Conflicting Data Curation Actions: Transparency Through Argument...
Reconciling Conflicting Data Curation Actions:  Transparency Through Argument...Reconciling Conflicting Data Curation Actions:  Transparency Through Argument...
Reconciling Conflicting Data Curation Actions: Transparency Through Argument...
 
Abortion pills in Jeddah |+966572737505 | get cytotec
Abortion pills in Jeddah |+966572737505 | get cytotecAbortion pills in Jeddah |+966572737505 | get cytotec
Abortion pills in Jeddah |+966572737505 | get cytotec
 
一比一原版(曼大毕业证书)曼尼托巴大学毕业证成绩单留信学历认证一手价格
一比一原版(曼大毕业证书)曼尼托巴大学毕业证成绩单留信学历认证一手价格一比一原版(曼大毕业证书)曼尼托巴大学毕业证成绩单留信学历认证一手价格
一比一原版(曼大毕业证书)曼尼托巴大学毕业证成绩单留信学历认证一手价格
 
Case Study 4 Where the cry of rebellion happen?
Case Study 4 Where the cry of rebellion happen?Case Study 4 Where the cry of rebellion happen?
Case Study 4 Where the cry of rebellion happen?
 

Lecture 3.pdf

  • 1. Graph-theoretic Models, Lecture 3, Segment 1 John Guttag MIT Department of Electrical Engineering and Computer Science 6.00.2X LECTURE 3 1
  • 2. Programs that help us understand the world and solve practical problems Saw how we could map the informal problem of choosing what to eat into an optimization problem, and how we could design a program to solve it Now want to look at class of models called graphs Computational Models 6.00.2X LECTURE 3 2
  • 3. Set of nodes (vertices) ◦ Might have properties associated with them Set of edges (arcs) each consisting of a pair of nodes ◦ Undirected (graph) ◦ Directed (digraph) ◦ Source (parent) and destination (child) nodes ◦ Unweighted or weighted What’s a Graph? 6.00.2X LECTURE 3 3
  • 4. Set of nodes (vertices) ◦ Might have properties associated with them Set of edges (arcs) each consisting of a pair of nodes ◦ Undirected (graph) ◦ Directed (digraph) ◦ Source (parent) and destination (child) nodes ◦ Unweighted or weighted What’s a Graph? 6.00.2X LECTURE 3 4 10 12 3
  • 5. To capture useful relationships among entities ◦ Rail links between Paris and London ◦ How the atoms in a molecule related to one another ◦ Ancestral relationships Why Graphs? 6.00.2X LECTURE 3 5
  • 6. A directed graph in which each pair of nodes is connected by a single path ◦ Recall the search trees we used to solve knapsack problem Trees: An Important Special Case 6.00.2X LECTURE 3 6
  • 7. World is full of networks based on relationships ◦ Computer networks ◦ Transportation networks ◦ Financial networks ◦ Sewer networks ◦ Political networks ◦ Criminal networks ◦ Social networks ◦ Etc. Why Graphs Are So Useful 6.00.2X LECTURE 3 7 mapr.com
  • 8. Graph Theory Saves Me Time Every Day 6.00.2X LECTURE 3 8 www.google.com
  • 9. Model road system using a digraph ◦ Nodes: points where roads end or meet ◦ Edges: connections between points ◦ Each edge has a weight indicating time it will take to get from source node to destination node for that edge Solve a graph optimization problem ◦ Shortest weighted path between my house and my office Getting John to the Office 6.00.2X LECTURE 3 9 CC-BY SusanLesch
  • 10. First Reported Use of Graph Theory 6.00.2X LECTURE 3 10 Bridges of Königsberg (1735) Possible to take a walk that traverses each of the 7 bridges exactly once?
  • 11. Leonhard Euler’s Model 6.00.2X LECTURE 3 11 Each island a node Each bridge an undirected edge Model abstracts away irrelevant details ◦ Size of islands ◦ Length of bridges Is there a path that contains each edge exactly once?
  • 12. Implementing graphs Some classic graph optimization problems Next Segment 6.00.2X LECTURE 3 12 CC-BY Juliaytsai94
  • 13. Graph-theoretic Models, Lecture 3, Segment 2 John Guttag MIT Department of Electrical Engineering and Computer Science 6.00.2X LECTURE 3 1
  • 14. Class Node 6.00.2X LECTURE 3 2 class Node(object): def __init__(self, name): """Assumes name is a string""" self.name = name def getName(self): return self.name def __str__(self): return self.name
  • 15. Class Edge 6.00.2X LECTURE 3 3 class Edge(object): def __init__(self, src, dest): """Assumes src and dest are nodes""" self.src = src self.dest = dest def getSource(self): return self.src def getDestination(self): return self.dest def __str__(self): return self.src.getName() + '->’ + self.dest.getName()
  • 16. Adjacency matrix ◦ Rows: source nodes ◦ Columns: destination nodes ◦ Cell[s, d] = 1 if there is an edge from s to d 0 otherwise Adjacency list ◦ Associate with each node a list of destination nodes Common Representations of Digraphs 6.00.2X LECTURE 3 4
  • 17. Class Digraph, part 1 6.00.2X LECTURE 3 5 class Digraph(object): """edges is a dict mapping each node to a list of its children""” def __init__(self): self.edges = {} def addNode(self, node): if node in self.edges: raise ValueError('Duplicate node') else: self.edges[node] = [] def addEdge(self, edge): src = edge.getSource() dest = edge.getDestination() if not (src in self.edges and dest in self.edges): raise ValueError('Node not in graph') self.edges[src].append(dest)
  • 18. Class Digraph, part 2 6.00.2X LECTURE 3 6 def childrenOf(self, node): return self.edges[node] def hasNode(self, node): return node in self.edges def getNode(self, name): for n in self.edges: if n.getName() == name: return n raise NameError(name) def __str__(self): result = '' for src in self.edges: for dest in self.edges[src]: result = result + src.getName() + '->' + dest.getName() + 'n' return result[:-1] #omit final newline
  • 19. Why is Graph a subclass of digraph? Remember the substitution rule from 6.00.1x? ◦ If client code works correctly using an instance of the supertype, it should also work correctly when an instance of the subtype is substituted for the instance of the supertype Any program that works with a Digraph will also work with a Graph (but not vice versa) Class Graph 6.00.2X LECTURE 3 7 class Graph(Digraph): def addEdge(self, edge): Digraph.addEdge(self, edge) rev = Edge(edge.getDestination(), edge.getSource()) Digraph.addEdge(self, rev)
  • 20. Shortest path from n1 to n2 ◦ Shortest sequence of edges such that ◦ Source node of first edge is n1 ◦ Destination of last edge is n2 ◦ For edges, e1 and e2, in the sequence, if e2 follows e1 in the sequence, the source of e2 is the destination of e1 Shortest weighted path ◦ Minimize the sum of the weights of the edges in the path A Classic Graph Optimization Problem 6.00.2X LECTURE 3 8
  • 21. Finding a route from one city to another Designing communication networks Finding a path for a molecule through a chemical labyrinth … Some Shortest Path Problems 6.00.2X LECTURE 3 9 CC-BY Juliaytsai94 www.google.com
  • 22. An Example 6.00.2X LECTURE 3 10 Boston Providence New York Chicago Denver Phoenix Los Angeles Adjacency List Boston: Providence, New York Providence: Boston, New York New York: Chicago Chicago: Denver, Phoenix Denver: Phoenix, New York Los Angeles: Boston
  • 23. Build the Graph 6.00.2X LECTURE 3 11 def buildCityGraph(): g = Digraph() for name in ('Boston', 'Providence', 'New York', 'Chicago', 'Denver', 'Phoenix', 'Los Angeles'): #Create 7 nodes g.addNode(Node(name)) g.addEdge(Edge(g.getNode('Boston'), g.getNode('Providence'))) g.addEdge(Edge(g.getNode('Boston'), g.getNode('New York'))) g.addEdge(Edge(g.getNode('Providence'), g.getNode('Boston'))) g.addEdge(Edge(g.getNode('Providence'), g.getNode('New York'))) g.addEdge(Edge(g.getNode('New York'), g.getNode('Chicago'))) g.addEdge(Edge(g.getNode('Chicago'), g.getNode('Denver'))) g.addEdge(Edge(g.getNode('Denver'), g.getNode('Phoenix'))) g.addEdge(Edge(g.getNode('Denver'), g.getNode(’New York'))) g.addEdge(Edge(g.getNode('Chicago'), g.getNode('Phoenix'))) g.addEdge(Edge(g.getNode('Los Angeles'), g.getNode('Boston')))
  • 24. Solutions to shortest path problem Coming Up 6.00.2X LECTURE 3 12
  • 25. Graph-theoretic Models, Lecture 3, Segment 3 John Guttag MIT Department of Electrical Engineering and Computer Science 6.00.2X LECTURE 3 1
  • 26. Algorithm 1, depth-first search (DFS) Similar to left-first depth-first method of enumerating a search tree (Lecture 2) Main difference is that graph might have cycles, so we must keep track of what nodes we have visited Finding the Shortest Path 6.00.2X LECTURE 3 2
  • 27. Depth First Search (DFS) 6.00.2X LECTURE 3 3 def DFS(graph, start, end, path, shortest): path = path + [start] if start == end: return path for node in graph.childrenOf(start): if node not in path: #avoid cycles if shortest == None or len(path) < len(shortest): newPath = DFS(graph, node, end, path, shortest, toPrint) if newPath != None: shortest = newPath return shortest def shortestPath(graph, start, end): return DFS(graph, start, end, [], None, toPrint) DFS called from a wrapper function: shortestPath Gets recursion started properly Provides appropriate abstraction
  • 28. Test DFS 6.00.2X LECTURE 3 4 def testSP(source, destination): g = buildGraph() sp = shortestPath(g, g.getNode(source), g.getNode(destination) if sp != None: print('Shortest path from', source, 'to', destination, 'is', printPath(sp)) else: print('There is no path from', source, 'to', destination) testSP('Boston', ’Chicago')
  • 29. An Example 6.00.2X LECTURE 3 5 Boston Providence New York Chicago Denver Phoenix Los Angeles Adjacency List Boston: Providence, New York Providence: Boston, New York New York: Chicago Chicago: Denver, Phoenix Denver: Phoenix, New York Los Angeles: Boston
  • 30. Current DFS path: Chicago Current DFS path: Chicago->Denver Current DFS path: Chicago->Denver->Phoenix Current DFS path: Chicago->Denver->New York Already visited Chicago There is no path from Chicago to Boston Output (Chicago to Boston) 6.00.2X LECTURE 3 6 Boston Providence New York Chicago Denver Phoenix Los Angeles
  • 31. Current DFS path: Boston Current DFS path: Boston->Providence Already visited Boston Current DFS path: Boston->Providence->New York Current DFS path: Boston->Providence->New York->Chicago Current DFS path: Boston->Providence->New York->Chicago->Denver Current DFS path: Boston->Providence->New York->Chicago->Denver->Phoenix Found path Already visited New York Current DFS path: Boston->New York Current DFS path: Boston->New York->Chicago Current DFS path: Boston->New York->Chicago->Denver Current DFS path: Boston->New York->Chicago->Denver->Phoenix Found a shorter path Already visited New York Shortest path from Boston to Phoenix is Boston->New York->Chicago->Denver->Phoenix Output (Boston to Phoenix) 6.00.2X LECTURE 3 7
  • 32. Algorithm 2: Breadth-first Search (BFS) 6.00.2X LECTURE 3 8 def BFS(graph, start, end, toPrint = False): initPath = [start] pathQueue = [initPath] if toPrint: print('Current BFS path:', printPath(pathQueue)) while len(pathQueue) != 0: #Get and remove oldest element in pathQueue tmpPath = pathQueue.pop(0) print('Current BFS path:', printPath(tmpPath)) lastNode = tmpPath[-1] if lastNode == end: return tmpPath for nextNode in graph.childrenOf(lastNode): if nextNode not in tmpPath: newPath = tmpPath + [nextNode] pathQueue.append(newPath) return None ? Explore all paths with n hops before exploring any path with more than n hops
  • 33. Want to minimize the sum of the weights of the edges, not the number of edges DFS can be easily modified to do this BFS cannot, since shortest weighted path may have more than the minimum number of hops What About a Weighted Shortest Path 6.00.2X LECTURE 3 9
  • 34. Graphs are cool ◦ Best way to create a model of many things ◦ Capture relationships among objects ◦ Many important problems can be posed as graph optimization problems we already know how to solve Depth-first and breadth-first search are important algorithms ◦ Can be used to solve many problems Recap 6.00.2X LECTURE 3 10
  • 35. Modeling situations with unpredictable events Will make heavy use of plotting ◦ Lecture 4 is about plotting in Python ◦ Identical to a lecture in 6.00.1x, feel free to skip it if you took 6.00.1x Coming Up 6.00.2X LECTURE 3 11