title: Find connected distinct elements in a two-dimensional array
body: <p>I thinking about this problem since two days and didn't find a practicable resolution:</p>
  
  <p>I have a two dimensional array and want to find the biggest number of items that are connected (horizontal and vertical, not diagonal) but no item of this group should be duplicate.</p>
  
  <p>Examples for possible groups:</p>
  
  <pre><code>--FG- or -F--- or -----
  --E--    -E---    ---AF
  -BC--    CBD--    ----B
  -AD--    -A---    --CDE
  </code></pre>
  
  <p>This is a simplified view of my problem because in "reality" the array is 6x9 and there are three different type of "elements" (lets say numbers, letters and symbols) with each 30 distinct possible items and a blank (-) element. In the first pass I check each position and find all connected items of the same elements. This was relatively easy to achieve with a recursive function, the field 0,0 is at the bottom left (another simplified view):</p>
  
  <pre><code>12AB-1-     The check for    -AB----  
  23CD23-     position 2:0     -CD----
  2*CE55-     ("C") would      --CE---
  #2E2*AA     result in        --E----
  #$A23BC     this:            --A----
  $$F1+*E                      --F----
  21C31*2                      --C----
  </code></pre>
  
  <p>The check for position 2:0 "C" would result in an array with 10 connected "letter" items. Now I search for the the biggest number of connected items in this new array that are distinct, so that are not two duplicate items in the new group. For position 2:0 this would result in max 4 connected distinct items, because you can not reach another item without touching an item that is already in the group (here another C).</p>
  
  <p>For my problem it is enough to detect max. 6 different connected items in the 10 items group.</p>
  
  <p>A possible group for the above example would be (when I check position 2:1 "F"):</p>
  
  <pre><code>--B----
  --D----
  --C----
  --E----
  --A----
  --F----
  -------
  </code></pre>
  
  <p>I don't find an algorithm that would do that, like the simple recursive function I use to find all the items of the same element in the array. It seems to be far more complex.</p>
  
  <p>For example the algorithm must also recognize that it don't add the E at position 3:4 to the group but the E at position 2:3.</p>
  
  <p>I think the above described intermediate step to first find alle connected items of an element is unneccessary, but at the moment I do this here and in my code to make things more clear :)</p>