Skip to content
Advertisement

how to traverse a Boolean recursion array

The exercise: Build a recursion(with no loops) that every cell that you go inside is the number of steps that you can go, it could be right/left until you get to the last cell. if you can’t get to the last cell return false, else return true. you must start from index 0.

My problem: I build the program, it’s not working, ,i am able to get to last cell but in the output i get false, i understand why i get false but i don’t know how to fix it.

Test:

JavaScript

Advertisement

Answer

Your condition for returning false is wrong.

JavaScript

should be

JavaScript

You want to return false if you can’t proceed either left or right. Your condition tests whether you can’t proceed both left and right.

EDIT:

My original suggested fix wasn’t enough, since your method must be able to back-track if you reach a dead end.

Here’s an alternative approach:

JavaScript

The idea is that if you can go both left and right, and going right leads to a dead end, you must try to go left when the recursive call for going right returns.

This returns true for both {1,4,3,6,1,2,4,3} and {2,4,1,6,4,2,4,3,5}.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement