Home > database >  Check the values of a matrix and jump in columns, using a recursion function
Check the values of a matrix and jump in columns, using a recursion function

Time:07-05

Say I have a matrix of only 0 and 1, something like this:

0 0 1 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 1 0

I start from the first column, and to move to the next column there is only three options, which are [i 1][j 1] or [i][j 1] or [i-1][j 1]. Clashing into 1 is not allowed. It needs to check those three directions and decide where to move.

preferably I want to go low, so [i-1][j 1] is the first option to concider. If not, then [i][j 1], and if not then [i 1][j 1]. If there is no way to go further without clashing into 1, ther is no solution, then the function returns 0. The goal is to get to the last column in the matrix, in the lowest row possible, and return the number of the row.

I'm writing a code to tell it exactly this, but I dont know what to fill for each if condition. How do I tell it to move in those directions, until the end of the matrix?

def jumpFromOnes(matrix,i,j):


if(mat[i][j] == 0):
    
    if(matrix[i 1][j 1] !=1 ):
        < fill here >
       
    elif (matrix[i][j 1] !=1):
        < fill here >
        
    elif (i==0 or matrix[i-1][j 1]!=1):
        < fill here >

# This is to tell it where to stop, if it got to the last column or the last row. Dont know if it's correct though.


 if(j 1<len(matrix[0])):
        jumpFromOnes(matrix,i,j 1)
    elif(i 1<len(matrix)):    
        jumpFromOnes(matrix,i 1,0)
    else:
        return
    

CodePudding user response:

Change your i and j indeces with i 1, i-1 or j 1 depending on which index you are 'jumping' to.

You should do this in a loop so it does it more than once. (If that is what you want)

If it is in a function return it to the outer scope so the indeces are constantly changed. (i.e. the i and j outside the function should be changed as well)

Edit: recursive function

def jumpFromOnes(mat,i,j):
    if i==len(matrix)-1: return "Reached end at bottom"
    if j==len(matrix[0])-1: return "Reached end at right"
    if not mat[i 1][j 1]: return jumpFromOnes(mat,i 1,j 1)
    if not mat[i][j 1]: return jumpFromOnes(mat,i,j 1)
    if not mat[i-1][j 1]: return jumpFromOnes(mat,i-1,j 1)
    return "Impossible to continue"

This works as it will first check if it reached one of the ends, then if matrix at new position i 1, i-1 or j 1 equals 0 (as not 1 -> 0 and not 0 -> 1, which are respectively equal to False or True in python) we return jumpFromOnes at that new position, and if none of the new positions are available, we return impossible to continue.

  • Related