0% found this document useful (0 votes)
1 views24 pages

Graph Theory - Removed

The document provides an overview of graph theory, focusing on algorithms and problem-solving techniques. It covers graph representation, traversal methods like Depth-First Search (DFS) and Breadth-First Search (BFS), classical algorithms such as Dijkstra's and Prim's, and applications including graph coloring and maze traversal. Additionally, it includes code examples for implementing these concepts in programming.

Uploaded by

Mauricio Rosero
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views24 pages

Graph Theory - Removed

The document provides an overview of graph theory, focusing on algorithms and problem-solving techniques. It covers graph representation, traversal methods like Depth-First Search (DFS) and Breadth-First Search (BFS), classical algorithms such as Dijkstra's and Prim's, and applications including graph coloring and maze traversal. Additionally, it includes code examples for implementing these concepts in programming.

Uploaded by

Mauricio Rosero
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Graph Theory:

Algorithms and Problem Solving


Nestor Diaz, Ph.D.
Table of contents
Graph Graph
01 02
Representation Traversal
Concepts and data structures. Depth-first search (DFS),
Breadth-first search (BFS).

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

Ο(𝑖𝑡𝑒𝑟𝑎𝑡𝑒 𝑣𝑒𝑟𝑡𝑖𝑐𝑒𝑠? )

Source: Sedgewick & Kayne, Algorithms, 4th Edition


Graph implementation

adjacency lists

create empty graph

add edge v-w

iterator for vertices adjacent to v


Graph implementation
public static void main(String[] args) {
13 vertices, 13 edges
In in = new In(args[0]);
0: 6 2 1 5
Graph G = new Graph(in);
1: 0
StdOut.println(G);
2: 0
}
3: 5 4
public String toString() { 4: 5 6 3
StringBuilder s = new StringBuilder(); 5: 3 4 0
s.append(V + " vertices, " + E + " edges "); 6: 0 4
for (int v = 0; v < V; v++) { 7: 8
s.append(v + ": "); 8: 7
for (int w : adj[v]) { 9: 11 10 12
s.append(w + " "); 10: 9
} 11: 9 12
s.append(NEWLINE); 12: 11 9
}
return s.toString();
}
02
Graph Traversal
Algorithms based in DFS/BFS
DFS Graph Traversal
public DepthFirstPaths(Graph G, int s) {
this.s = s;
edgeTo = new int[G.V()];
marked = new boolean[G.V()];
validateVertex(s);
dfs(G, s);
}

// depth first search from v


private void dfs(Graph G, int v) {
marked[v] = true;
for (int w : G.adj(v)) {
if (!marked[w]) {
edgeTo[w] = v;
dfs(G, w);
}
}
}
DFS Graph Traversal
// depth first search from v
private void dfs(Graph G, int v) {
1→ marked[v] = true;
for (int w : G.adj(v)) {
7↓ 6→
if (!marked[w]) {
5↑ edgeTo[w] = v;
2↓
dfs(G, w);
4↑ }
←3 }
}

Content edgeTo array:


0 1 2 3 4 5 6 7 8 9 10 11 12

5 0 0 5 6 4 0
DFS Graph Traversal

public Iterable<Integer> pathTo(int v) {


validateVertex(v);
if (!hasPathTo(v)) return null;
Stack<Integer> path = new Stack<Integer>();
for (int x = v; x != s; x = edgeTo[x])
path.push(x);
path.push(s);
return path;
}
Content edgeTo array:
0 1 2 3 4 5 6 7 8 9 10 11 12

5 0 0 5 6 4 0

Path from vertex 0 to vertex 3:


0 →6 → 4 → 5 → 3
DFS Application: Maze traversal

Find the path from S to G in the following maze: Solution:

1st step: Enumerate cells from 0 to 9x9.


Each cell is a node in the graph.
nd
2 step: Set edges for connected cells.
Wall nodes have no edges.
rd
3 step: Call dfs method to search paths
with node S as source.
th
4 step: Find the path that starts at node S
and ends at node G.
DFS Application: Maze traversal
Graph input:
Nodes numbering: 81
52
01 22 23 44 53 74 65
09 22 31 45 54 75 74
12 23 24 47 56 75 76
23 24 25 49 58 76 77
2 11 24 33 51 60 77 78
34 25 26 53 62 78 79
6 15 26 35 54 63 79 80
8 17 27 36 56 65
9 18 29 38 60 69
11 20 31 40 62 71
15 24 35 44 63 72
17 26 36 45 69 78
18 27 38 47 71 80
20 29 40 49 72 73
42 51 74 73
DFS Application: Maze traversal

Nodes numbering: Graph segment:


DFS Application: Maze traversal

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 = Integer.parseInt(args[2]);
DepthFirstPathsMaze dfs = new DepthFirstPathsMaze(G, s);
if (dfs.hasPathTo(g)) {
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);
}
}
DFS Application: Maze traversal

Nodes numbering: Solution:

>java DepthFirstPathsMaze maze1.txt 51 4

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?

Nodes numbering: Solution:

>java DepthFirstPathsMaze maze1.txt 51 4 6 8

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

ACM/ICPC Problem example


private void dfs(Graph G, int v) {
marked[v] = true;
for (int w : G.adj(v)) {
if (cycle != null) return;
if (!marked[w]) {
edgeTo[w] = v;
color[w] = !color[v];
dfs(G, w);
}
else if (color[w] == color[v]) {
isBipartite = false;
cycle = new Stack<Integer>();
for (int x = v; x != w; x = edgeTo[x]) {
cycle.push(x);
}
cycle.push(w);
}
}
}
public static void main(String[] args) {
In in = new In(args[0]);
try{
for(int i=0; i<200; i++){
Graph G = new Graph(in);
Bicoloring b = new Bicoloring(G);
if (b.isBipartite()) {
StdOut.println("BICOLORABLE");
}
else {
StdOut.println("NOT BICOLORABLE");
}
}
}catch (IllegalArgumentException e) {System.exit(0); }
}
public Graph(In in) { File graph reading
try {
this.V = in.readInt();
if (V <= 0) throw new IllegalArgumentException("Empty Graph!");
adj = (Bag<Integer>[])new Bag[V];
for (int v = 0; v < V; v++) {
adj[v] = new Bag<Integer>();
}
int E = in.readInt();
if (E < 0) throw new IllegalArgumentException("number of edges ...");
for (int i = 0; i < E; i++) {
int v = in.readInt();
int w = in.readInt();
validateVertex(v);
validateVertex(w);
addEdge(v, w);
}
}
catch (NoSuchElementException e) {
throw new IllegalArgumentException("invalid input ....", e);
}}
http://poj.org/problem?id=1419
Time Limit: 1000MS Memory Limit: 10000K
Graph Coloring
Total Submissions: 7456 Accepted: 3418
Description
You are to write a program that tries to find an optimal coloring for a given graph. Colors are applied to the nodes
of the graph and the only available colors are black and white. The coloring of the graph is called optimal if a
maximum of nodes is black. The coloring is restricted by the rule that no two connected nodes may be black.
Input
The graph is given as a set of nodes denoted by numbers 1...n, n <= 100, and a set of
undirected edges denoted by pairs of node numbers (n1, n2), n1 != n2. The input file
contains m graphs. The number m is given on the first line. The first line of each graph
contains n and k, the number of nodes and the number of edges, respectively. The following
k lines contain the edges given by a pair of node numbers, which are separated by a space.
Figure 1: An Output
optimal graph with The output should consists of 2m lines, two lines for each graph found in the input file. The
three black nodes first line of should contain the maximum number of nodes that can be colored black in the
graph. The second line should contain one possible optimal coloring. It is given by the list
of black nodes, separated by a blank.

You might also like