Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First: recursion solution in Clear category for Can You Pass? by Red_Ale
def can_pass(matrix, first, second):
def move(x, y, movement, no_back):
# This function move the cursor in the 4 directions. If symbol matches, it returns: position of next
# cell and the position to NOT check for the next move (i.e. from where you come from).
# no_back is according to position in array: coming from [down=0, up=1, right=2, left=3]
if movement == 'U':
if x == 0: return None
else: x -= 1
if movement == 'D':
x += 1
if movement == 'L':
if y == 0: return None
else: y -= 1
if movement == 'R':
y += 1
try:
if matrix[x][y] == symbol:
return (x, y), no_back
except IndexError:
return None
def loopOfControl (position, x, y):
test = any(position)
no_way = False # Flag to check if there is any direction where to go
while test: # It moves the cursor ahead until True.
position_copy = position.copy()
for item in position_copy: # this loop clean the list from useless value
if item == None:
position.remove(item)
if len(position) > 1: # if more than a choice is available, it starts to check all possible ways
for item in position:
no_way, solut = loopOfControl(list((item,)), x, y)
if solut == None: continue
return no_way, solut
for i in position:
if position[0][0] in previous_move: # if already visited, exit from loop
return no_way, None
x = i[0][0]
y = i[0][1]
no_back = i[1] # You can't check the cell from where you come from (removed later with pop).
if (x, y) == second: # Check if we arrived to target cell
return no_way, True
previous_move.append(position[0][0]) # it adds position to already visited cell
position = [move(x, y, 'U', 1), move(x, y, 'D', 0), move(x, y, 'L', 3), move(x, y, 'R', 2)]
position.pop(no_back)
test = any(position)
if not test:
no_way = True # if no other direction to go, flag is True
return no_way, None
if no_way == True: return False # if blocked, it's False
return no_way, None
x, y = first[0], first[1]
symbol = matrix[x][y]
previous_move = [(x, y)] # to avoid to check a cell already visited
# Next list checks if any next cell contains our symbol
position = [move(x, y, 'U', 1), move(x, y, 'D', 0), move(x, y, 'L', 3), move(x, y, 'R', 2)]
no_way, solut = loopOfControl(position, x, y)
if solut == None:
return False
return solut
if __name__ == '__main__':
assert can_pass(((0, 0, 0, 0, 0, 0),
(0, 2, 2, 2, 3, 2),
(0, 2, 0, 0, 0, 2),
(0, 2, 0, 2, 0, 2),
(0, 2, 2, 2, 0, 2),
(0, 0, 0, 0, 0, 2),
(2, 2, 2, 2, 2, 2),),
(3, 2), (0, 5)) == True, 'First example'
assert can_pass(((0, 0, 0, 0, 0, 0),
(0, 2, 2, 2, 3, 2),
(0, 2, 0, 0, 0, 2),
(0, 2, 0, 2, 0, 2),
(0, 2, 2, 2, 0, 2),
(0, 0, 0, 0, 0, 2),
(2, 2, 2, 2, 2, 2),),
(3, 3), (6, 0)) == False, 'First example'
print("The mission is completed? Click 'Check' to earn cool rewards!")
June 27, 2022
Comments: