1 3 BruteForceAlgorithms
1 3 BruteForceAlgorithms
Algorithmic Thinking
Luay Nakhleh
Department of Computer Science
Rice University
Bipartite Graphs
Algorithms Demo
Algorithm 1: IsBipartite.
Input: Undirected graph g = (V, E).
Output: True if g is bipartite, and False otherwise.
1 foreach Non-empty subset V1 V do
2
V2
V \ V1 ;
3
bipartite
T rue;
4
foreach Edge {u, v} 2 E do
5
if {u, v} V1 or {u, v} V2 then
6
bipartite
F alse;
7
Break;
8
9
10
Graph Connectivity:
Paths
A path is simple if it does not contain the same node more than once.
A cycle is a simple path that begins and ends at the same node.
A path (not necessarily simple) that begins and ends at the same node is called a
circuit.
5
Algorithm 2: IsConnected.
Input: Undirected graph g = (V, E), |V | 2, and two nodes u, v 2 V , such that u 6= v.
Output: T rue if there is a path between u and v in g, and F alse otherwise.
1
2
3
4
5
6
7
8
9
10
11
12
13
N odes
V {u, v};
for c
0 to |N odes| do
x0
u;
xc+1
v;
foreach subset W N odes of size c do
foreach permutation x1 , . . . , xc of the elements of W do
Connected
T rue;
for i
0 to c do
if {xi , xi+1 } 2
/ E then
Connected
F alse;
Break;
if Connected = T rue then
return True;
return False;
6
10
11
x2
x3
x4
y1
y2
ab
bbaaba
bb
y3
y4
bbbb ab
12
x2
x3
x4
y1
y2
ab
bbaaba
bb
y3
y4
bbbb ab
12
x2
x3
x4
y1
y2
ab
bbaaba
bb
y3
y4
bbbb ab
x1
x2
y1
y2
ab
ba
12
x2
x3
x4
y1
y2
ab
bbaaba
bb
y3
y4
bbbb ab
x1
x2
y1
y2
ab
ba
No Solution!
12
13
14
15