0

I have a CS problem which is stated like that:

Given a sheet of paper with some cells cut out, represented by chars (either '.' (cut) or '#' (not cut)), I need to find how many pieces will form.

Example:

##..#####.
.#.#.#....
###..##.#.
..##.....#
.###.#####

Answer for the example above is 5.

One piece will form:

....
.##.
....

Two pieces will form:

....
.#..
..#.

Common sense suggests me to find a way to represent a sheet with a graph (each number sign is a vertex, and two vertices are connected if they share a side). However, it is unclear to me how to do it. I found out that there are implicit graphs (graphs defined by a function which returns all neighbors of given vertex). A function like this is trivial to implement in the case.

The question is: How should I modify DFS algorithm to find components in this kind of graph?

1 Answers1

1
  1. When we loop over the edges from a vertex, we use implicit edges instead of stored edges.

  2. It is useful to represent vertices as their two-dimensional coordinates (row, col).

The pseudocode can be as follows:

dRow = [-1,  0, +1,  0]
dCol = [ 0, -1,  0, +1]
...later, when we want to move from vertex (row, col)...
for dir in [0..4):
    nRow = row + dRow[dir]
    nCol = col + dCol[dir]
    if vertex (nRow, nCol) is in rectangle bounds:
        try to move from vertex (row, col) to vertex (nRow, nCol)

That's in the place where a classic DFS implementation would have a loop like:

for each vertex u in {neighbors of vertex v}:
    try to move from vertex v to vertex u
Gassa
  • 8,546
  • 3
  • 29
  • 49