13
votes

# Programming Challenge: Shape detection.

The programming challenges have kind of come to a grinding halt recently. I think it's time to get another challenge started!

Given a grid of symbols, representing a simple binary state of "filled" or "unfilled", determine whether or not a square is present on the grid. Squares must be 2x2 in size or larger, must be completely solid (i.e. all symbols in the NxN space are "filled"), and must not be directly adjacent to any other filled spaces.

Example, where `0`

is "empty" and `1`

is "filled":

```
000000
011100
011100
011100
000010
// Returns true.
```

```
000000
011100
011100
011110
000000
// Returns false.
```

```
000000
011100
010100
011100
000000
// Returns false.
```

For those who want a greater challenge, try any of the following:

- Get a count of all squares.
- Detect squares that are touching (but not as a rectangle).
- Detect other specific shapes like triangles or circles (you will need to be creative).
- If doing (1) and (3), count shapes separately based on type.
- Detect shapes within unfilled space as well (a checkerboard pattern is a great use case).

Python 2.7:

This operates by searching the grid from top to bottom for horizontal segments of 2 or more contiguous filled cells within a row, then starting a search anchored from each contiguous segment found for a shape like:

(arbitrarily scalable)

If any such shape is found, then the grid contains a square.

I iterated on this a little too much and ended up with a thing that finds all the squares in the input grid and prints the grid back out with all of the squares bolded.

Fun thing: save a 2D 0's and 1's Menger sponge generated by this script and pass it to my python script to see it highlight everything nicely.