I am given a matrix containing only 1's and 0's, where adjacent 1's (horizontal or vertical, NOT diagonal) form rivers. I am asked to return an array of all river sizes in the matrix.
(Note the order of the river sizes don't matter- they can be in any order) i.e. [2,1,2,2,5] is also a valid solution!
I am writing the recursive part of the code, where as we explore the matrix, if we stumble on a 1, we will run a recursion to explore its adjacent left, right,up and down for any 1's.
The code is quite lengthy, and I don't believe it is necessary for my question. My question is, as I call on the recursive function, and I update currentRiverSize +1 (initialised as 0) in the argument of the recursive function as we stumble across more 1's, can I then at the end simply append this to the array?
I have a feeling the recursion is not structured correctly!
def findAllRiverSizes(matrix):
riverSizes = []
exploreRiver(matrix,row,col,entryExplored,riverSizes,0):
def exploreRiver(matrix,row,col,entryExplored,riverSizes,currentRiverSize):
#look right:
if col<len(matrix[0])-1 and not entryExplored[row][col+1] and matrix[row][col+1] == 1:
entryExplored[row][col+1] = True
exploreRiver(matrix,row,col+1,entryExplored,riverSizes,currentRiverSize +1)
#look left
if col>0 and not entryExplored[row][col-1] and matrix[row][col-1] == 1:
entryExplored[row][col-1] = True
exploreRiver(matrix,row,col-1,entryExplored,riverSizes,currentRiverSize +1)
#look up
if row >0 and not entryExplored[row-1][col] and matrix[row-1][col] == 1:
entryExplored[row-1][col] = True
exploreRiver(matrix,row-1,col,entryExplored,riverSizes,currentRiverSize +1)
#look down
if row <len(matrix)-1 and not entryExplored[row+1][col] and matrix[row+1][col] == 1:
entryExplored[row+1][col] = True
exploreRiver(matrix,row+1,col,entryExplored,riverSizes,currentRiverSize +1)
riverSizes.append(currentRiverSize)
return riverSizes
