Module 2.1. 1-0 BFS and Modular Arithmetic2014-10

advertisement
An Introduction to Modular Arithmetic
x ≡ y mod m
y is the remainder were you to divide x by m
Example where m = 2
2 fits twice into 5 and leaves a remainder of 1
Therefore, 5 ≡ 1 mod 2
Also, in programming, the mod operator is represented by %
So 5 %2 = 1
Why use ≡ instead of = ?
What is 7 % 2? What is 1135 % 2 ?
Both are equal to one, however, the 1135 and the 7 can both be reduced to say, 1.
So we say they are congruent to 1, rather than equal to it.
The ≡ symbol is for congruency.
When is it useful in programming?
Problem: You are given a value of s seconds, output the number of minutes and seconds (M:S), the
number of digits doesn’t matter.
Input: 85 seconds
60 seconds in a minute, M = 85/60 (rounds down by chopping off decimal)
S = 85%60 => 25
So the output is 1:25
Modular Arithmetic is actually very useful:
2a – 5b = 4
2a + 3b = 3
Can a and b be integers?
Another example:
18x2 + 39x – 7 = 0.
Quick: Is x an integer? No paper or calculators allowed.
18 and 39 are both factors of 3
0x2+ 0x + 2 ≡ 0 mod 3
Notice that -7 ≡ 2 mod 3
However, 2 ≡ 0 mod 3, which is a contradiction.
Therefore, there are no integer solutions for x.
Even more examples:
12%4=
14%22=
5 ≡ 2 mod 3
5%3 =
2%3 =
Now let’s talk about BFS vs. DFS
What’s the difference?
Breadth First Search | Depth First Search
Let’s discuss:
Say you have a grid, represented with (row, column) – and zero-indexed!
You Start at 1,1 and wish to walk to 4,4. How many steps will you take?
0,0
1,0
2,0
3,0
4,0
0,1
1,1
2,1
3,1
4,1
0,2
1,2
2,2
3,2
4,1
0,3
1,3
2,3
3,3
4,3
How can you convert the method you used into an algorithm?
0,4
1,4
2,4
3,4
4,4
0,5
1,5
2,5
3.5
4,5
But now, let’s add a twist – teleportation devices!
0,0
1,0
2,0
3,0
4,0
0,1
1,1 Start
2,1
3,1
4,1
0,2
1,2
2,2
3,2
4,1
0,3
1,3
2,3
3,3
4,3
0,4
1,4
2,4
3,4
4,4 End
0,5
1,5
2,5
3.5
4,5
There are two pairs. Stepping on one will take you to its pair - instantly.
What strategy will you use to find the number of steps required for the shortest path?
Problem Set:
CCC 2008 S3 Maze – Solution is available at http://files.dmoj.tk => Senior => MazeCCC2008
CCC 2005 S5 Pinball – Also available in the same folder
Remember the sample BFS problem from last week? Try adding a teleportation device between any two
points and see what the shortest distance will then be. Can placing the teleportation devices
strategically actually increase the length of the shortest path?
Download