Graph Problems.pptx

advertisement
Graph Problems
As you arrive, think about this. Imagine I give you a graph
represented as a boolean adjacency matrix (so if
graph[2][33] == true, then you can travel from 2 to 33). I
want to write a function to determine if there is a path
between two nodes. What is an algorithm to do that?
Also, snarf the code for today’s
class.
For example, there is a path from
1 to 6 in this graph. There is no
path from 4 to 1.
What is the big O of the best possible algorithm to
determine if there is a path between two nodes
on a graph? (n is the number of nodes in the
graph)
1.O(log n)
2.O(n)
3.O(n2)
4.O(n log n)
For example, there is a path from
1 to 6 in this graph. There is no
path from 4 to 1.
The Plan for Today
1.
2.
3.
4.
Graphs – does a path exist?
You solve some problems with graphs
Depth first search vs. Breadth first search
You use a queue to solve another problem
with graphs
5. Course evaluations
Write hasCycle
Write isStronglyConnected
You can use the existing pathExists function
Test your code on the 3 sample graphs included in main
Once you finish with the straightforward solutions, try to come
up with more efficient solutions
Graph 1 (no cycles)
Graph 2
Graph 3
Depth First Search vs.
Breadth First Search
1. Depth First Search usually uses recursion
2. Breadth First Search uses a queue
3. Breadth First Search visits elements in order of
distance, so it’s what you want if you’re looking for
a shortest path
4. In both, you must be careful not to revisit nodes
you have already visited (otherwise you’ll have
problems with cycles)
Write lastNodeOnShortestPath
• Returns the last node in the
shortest path between two
elements
• Should use a queue
• You can assume there is a path
between the nodes
• If you finish, write
shortestPathDistance which
returns the length of the
lastNodeOnShortestPath(7,3)
shortest path
would return 0
• If you need a hint, this is actually
pretty similar to the word chains
problem on Practice Exam 2
• When you’re done please submit
via Ambient
Student Evaluations
1. Student evaluations are treated very seriously by
teachers and administrators. They can affect
things like hiring and promotion.
2. I read every one of my evaluations carefully
(often I’ll go through them several times and
take notes) and I often revise my courses based
on the feedback .
3. If you can spend the time to write a detailed
response (be it positive, negative, or mixed), I
very much appreciate it.
4. The code for this course is 6966
5. I have uploaded a link to the major/minor
codesheet in the resources section of Sakai. I
also have one up front.
Download