Graph Theory - Removed
Graph Theory - Removed
03 04
Classical Algorithms Applications
Shortest path, Diksjtra, Prim, Graph coloring, Planar graphs,
Kruskal. problem solving.
Graph implementation
Input format:
Graph implementation
two entries for each edge
Ο(𝑖𝑡𝑒𝑟𝑎𝑡𝑒 𝑣𝑒𝑟𝑡𝑖𝑐𝑒𝑠? )
adjacency lists
5 0 0 5 6 4 0
DFS Graph Traversal
5 0 0 5 6 4 0
Output:
51→60→69→78→77→76→75→74→65→56→47→38→29→20→11→2→3→4
Suppose that there are several goals. How to find paths from S to the goals?
DFS Application: Maze traversal
Suppose that there are several goals. How to find paths from S to the goals?
Output:
51→60→69→78→77→76→75→74→65→56→47→38→29→20→11→2→3→4
51→60→69→78→79→80→71→62→53→44→35→26→25→24→15→6
51→60→69→78→79→80→71→62→53→44→35→26→17→8
DFS Application: Maze traversal
Multiple Goals
Nodes numbering: Solution code:
public static void main(String[] args) {
In in = new In(args[0]);
Graph G = new Graph(in);
int s = Integer.parseInt(args[1]);
int[] g = new int[args.length-2];
DepthFirstPathsMaze dfs = new DepthFirstPathsMaze(G, s);
for (int i = 2; i < args.length; i++) {
g[i-2] = Integer.parseInt(args[i]);
if (dfs.hasPathTo(g[i-2] )) {
for (int x : dfs.pathTo(g)) {
if (x == s) StdOut.print(x);
else StdOut.print("-" + x);
}
}
else {
StdOut.printf(“NO path from %d to %d!", s, g[i-2]);
}}
}
04
Applications
Problem solving with graphs
Problem Description