Chapter 3
Chapter 3
Brute Force
Gedamu A.
[email protected]
Image processing and Computer vision SIG
Some of the sides are exported from different sources to clarify the topic
Introduction
Brute Force
A straightforward approach:
usually based directly on the problem’s statement
definitions of the concepts involved
Examples:
1. Computing an (a > 0, n a nonnegative integer)= a*a*….*a
2. Computing n!
Brute-force algorithm
Step 1 Align pattern at beginning of text
Step 2 Moving from left to right, compare each character of
pattern to the corresponding character in text until
─ all characters are found to match (successful search); or
─ a mismatch is detected
Step 3 While pattern is not found and the text is not yet
exhausted, realign pattern one position to the right and
repeat Step 2
1. Pattern: 001011
Text: 10010101101001100101111010
2. Pattern: happy
Text: It is never too late to have a happy childhood.
for i n downto 0 do
power 1
for j 1 to i do //compute xi
power power x
p p + a[i] power
return p
Find the two closest points in a set of n points (in the two-
dimensional Cartesian plane).
Brute-force algorithm
Compute the distance between every pair of distinct points
and return the indexes of the points for which the distance is
the smallest.
Weaknesses
rarely yields efficient algorithms
some brute-force algorithms are unacceptably slow
not as constructive as some other design techniques
c 7 d
How do we represent a solution (Hamiltonian circuit)?
Computer Science and Engineering Program:DAA
Gedamu Alemu
TSP by Exhaustive Search
Tour Cost
a→b→c→d→a 2+3+7+5 = 17
a→b→d→c→a 2+4+7+8 = 21
a→c→b→d→a 8+3+4+5 = 20 2
a→c→d→b→a 8+7+4+2 = 21
a b
5 3
a→d→b→c→a 5+4+3+8 = 20 8 4
a→d→c→b→a 5+7+3+2 = 17
Efficiency: c 7 d
Θ((n-1)!)
Given n items:
weights: w1 w2 … wn
values: v1 v2 … vn
a knapsack of capacity W
Find most valuable subset of the items that fit into the knapsack
2,1,3,
Computer Science and Engineering Program:DAA
4 Gedamu Alemu
Final Comments on Exhaustive Search
Exhaustive-search algorithms run in a realistic amount of time only on
very small instances
In many cases, exhaustive search or its variation is the only known way to
get exact solution
Using Stack
a vertex is pushed onto the stack when it’s reached for the first time
a vertex is popped off the stack when it becomes a dead end, i.e., when
there is no adjacent unvisited vertex
a b c d
e f g h
DFS tree:
a b c d
abgcdh
abgcd
abgcd
abgc
abfe
e f g h
abg
abf
abf
ab
ab
4 3 5 8
…
a
Red edges are tree edges and other edges are back
edges.
Applications:
checking connectivity, finding connected components
checking a cyclicity (if no back edges)
a b c d
e f g h
BFS tree:
1 2 6 8
BFS traversal queue: a b c d
e f g h
3 4 5 7
bef
efg
hd
ch
fg