# Scala algorithm: Count number of contiguous countries by colors

Published , last updated

## Algorithm goal

Given a grid of colors describing a map of countries, where a contiguous blob of colour represents a country, count the number of countries on the map. A country can span diagonally. For example, in the map below, there are 7 distinct countries.

## Test cases in Scala

```
assert(CountryCounter(CountryMapCoded).countCountries == 7)
```

## Algorithm in Scala

67 lines of Scala (version 2.13).

## Explanation

This problem is an application of breadth-first search: for each position, we consume as many sibling nodes as we can that are of the same color. When we find no more after repeated iteration, we have found a country (a set of positions). Then, we only consider nodes left over that do not belong in any country that was selected, and repeat again. Eventually we find the set of countries as well as the size (count) of this set.

Take special note of Scala's set operations which are very powerful. (this is Â© from www.scala-algorithms.com)

## Scala concepts & Hints

### Class Inside Class

A great aspect of Scala is being able to declare classes in other classes. This allows one to reduce repetition and for example refer to values of the outer class effortlessly.

### Def Inside Def

A great aspect of Scala is being able to declare functions inside functions, making it possible to reduce repetition.

It is also frequently used in combination with Tail Recursion.

### For-comprehension

The for-comprehension is highly important syntatic enhancement in functional programming languages.

### Pattern Matching

Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it.

### Range

The

`(1 to n)`

syntax produces a "Range" which is a representation of a sequence of numbers.### Stack Safety

Stack safety is present where a function cannot crash due to overflowing the limit of number of recursive calls.

This function will work for n = 5, but will not work for n = 2000 (crash with java.lang.StackOverflowError) - however there is a way to fix it :-)

In Scala Algorithms, we try to write the algorithms in a stack-safe way, where possible, so that when you use the algorithms, they will not crash on large inputs. However, stack-safe implementations are often more complex, and in some cases, overly complex, for the task at hand.

### Tail Recursion

In Scala, tail recursion enables you to rewrite a mutable structure such as a while-loop, into an immutable algorithm.