I have a 2D array in Python (version 3.2) that looks like this:
...AAA....
...AAABB..
..BBBBBCC.
.....CCCC.
.DDD..CC..
.DDD......
It represents a kind of map with areas painted different colors. The above example shows four distinct regions, A, B, C, and D.
Here’s an example of indexing the array:
map[1][5] == ‘A’ would return True.
I’m trying to write a function that takes in an array like this, and a row/col index, and returns the number of adjoining spaces that are of the same “color”. So using that example above, here are some return values (the arguments are the array, row, and column number respectively:
6 <-- countArea(map, 5, 2)
8 <-- countArea(map, 2, 8)
I’d like to implement this as a recursive function, but I can’t figure it out. Here’s what I have so far:
def countArea(map, row, col):
key = map[row][col]
if (map[row-1][col] == key):
return 1 + countArea(map, row-1, col)
elif (map[row+1][col] == key):
return 1 + countArea(map, row+1, col)
elif (map[row][col+1] == key):
return 1 + countArea(map, row, col+1)
elif (map[row][col-1] == key):
return 1 + countArea(map, row, col-1)
else:
return 1
I know I’m missing something basic here. I’m basically saying “here is the current character, now look in each direction to see if it has the same character.”
My question is, what am I missing in this recursive definition?
Thanks for your help.
Once a grid square has been counted, it must not be counted again (this includes counting by recursive invocations of
countArea()!)Your current algorithm goes as far north as it can, and then keeps taking one step to the south followed by one step to the north. This two-step sequence repeats until you run out of stack space.
If you like, you could read up on algorithms for this problem in Wikipedia.