L1[1..4] = [2->3, 1->4, 1->4, 2->3]
Queue order with parents:
(∅,1),(1,2),(1,3),(2,1),(2,4),(3,1),(3,4),...
^ ^ ^ ^
A
/ \
B C
|
D
L2[1..4] = [3->2, 1->4, 1->4, 2->3]
Queue order with parents:
(∅,1),(1,3),(1,2),(3,1),(3,4),(2,1),(2,4),...
^ ^ ^ ^
A
/ \
C B
|
D
L1_adj_list <- list(c(2,3,4,6),
c(1,4),
c(1,5),
c(1,2),
c(3),
c(1))
L2_adj_list <- list(c(2,4),
c(1,3,4,6),
c(2,5),
c(1,2),
c(3),
c(2))
Examples:
If our problem has these two operations on “things” and “pairings”, then it reduces to a graph problem.
Problem: Color contiguous regions of a raster image with the same color.
Crude Paint Fill Tool: https://viliusle.github.io/miniPaint/
Reduction: Do BFS (or DFS) and instead of marking the vertices, paint them.
A raster image is an array P[1..m, 1..n]
of pixel colors.
P[i,j]
.P[i,j]
, its neighbors are P[i+1,j]
, P[i-1,j]
, P[i,j+1]
, P[i,j-1]
, unless these have different color values or are out of range.So Paint Fill reduces to WFS, where “mark” means “change the color to the paint color”
Modify BFS to match the reduction:
BreadthFirstSearch(s): PaintFill(i,j, fillColor, P[1..m, 1..n]):
bgColor <- P[i,j].color
Enqueue(s) Enqueue((i,j))
while the queue is not empty while the queue is not empty
v <- Dequeue (v1,v2) <- Dequeue
if v is unmarked if P[v1,v2].color == bgColor
mark v P[v1,v2].color <- paintColor
for each edge vw if i+1 <= m AND P[i+1,j].color == bgColor
Enqueue(w) Enqueue((i+1,j))
if i-1 >= 1 AND P[i-1,j].color == bgColor
Enqueue((i-1,j))
if j+1 <= n AND P[i,j+1].color == bgColor
Enqueue((i,j+1))
if j-1 >= 1 AND P[i,j-1].color == bgColor
Enqueue((i,j-1))
We could clean this up a little, but it should work.
\[ \begin{array}{|c|c|c|c|c|} \hline \color{red}3 & 5 & 7 & 4 & 6 \\ \hline 5 & 3 & 1 & 5 & 3 \\ \hline 2 & 8 & 3 & 1 & 4 \\ \hline 4 & 5 & 7 & 2 & 3 \\ \hline 3 & 1 & 3 & 2 &\color{green} * \\ \hline \end{array} \]
Table #1 | Table #2 | Table #3 | Table #4 | Table #5 | Table #6 | Table #7 |
---|---|---|---|---|---|---|
John | Claire | Andrew | Bri | Josiah | Isaac | Grace |
Jordan | Trevor | Nathan | James | Kristen | Ethan | Kevin |
Talia | Logan | Blake | Graham | Drake | Levi | Jack |
Let M[1..n, 1..n]
be an array of numbers, representing a Number Maze.
Describe a reduction. Specifically, given a vertex M[i,j]
, what vertices are its neighbors? Is the graph directed or undirected?
What kind of search is appropriate: DFS or BFS? Why?
In the WFS search algorithm (whichever it is), when should we stop?