Program to check we can cross river by stones or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of sorted numbers called stones and this is representing the positions of stones on a river that we are trying to cross. To cross the river, we must finish at the last stone. Now in each step, we can jump (k - 1, k, or k + 1) steps ahead where k is the distance of the last jump. We have to check whether we can cross the river or not.

So, if the input is like stones = [0, 1, 3, 4, 5, 6, 8, 9, 13], then the output will be True, as we can start from 0, then jump 1 unit to go stone 1, then 2 units to go 3, after that 2 units to 5, then 3 units to go 8, and finally 5 units to go 13, and this is the final place.

To solve this, we will follow these steps −

• start := A[0], end := last element of A
• A := a set of all unique elements of A
• Define a function check() . This will take pos:= start, prev:= 0
• if pos is same as end, then
• return True
• for each jump in [prev - 1, prev, prev + 1], do
• if jump >= 1, then
• next_pos := jump + pos
• if next_pos is in A and check(next_pos, jump) is true, then
• return True
• return False
• From the main method call check() and return result

Example (Python)

Let us see the following implementation to get better understanding −

Live Demo

class Solution:
def solve(self, A):
start, end = A[0], A[-1]
A = set(A)
def check(pos=start, prev=0):
if pos == end:
return True
for jump in [prev - 1, prev, prev + 1]:
if jump >= 1:
next_pos = jump + pos
if next_pos in A and check(next_pos, jump):
return True
return False
return check()
ob = Solution()
stones = [0, 1, 3, 4, 5, 6, 8, 9, 13]
print(ob.solve(stones))

Input

[0, 1, 3, 4, 5, 6, 8, 9, 13]

Output

True
Published on 12-Dec-2020 09:29:42