Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Recursive walk solution in Speedy category for Find Sequence by Ch0bits
def checkio(m):
commands = {
'U': (-1, 0),
'D': (1, 0),
'L': (0, -1),
'R': (0, 1)
}
def walk(row, col, prev, counter, command):
# move to next cell
for x in command:
x, y = commands[x]
row += x
col += y
# check for unreachable cell position
if row >= len(m) or col >= len(m) or row < 0 or col < 0:
return counter
# if the cell is different from the previous there is no victory
if m[row][col] != prev:
return counter
counter += 1
return walk(row, col, prev, counter, command)
# walk through every matrix cell
for row in range(len(m)):
for col in range(len(m)):
# go to every direction
for command in ['U', 'UR', 'R', 'RD', 'D', 'DL', 'L', 'LU']:
if walk(row, col, m[row][col], 1, command) == 4:
return True
return False
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio([
[1, 2, 1, 1],
[1, 1, 4, 1],
[1, 3, 1, 6],
[1, 7, 2, 5]
]) == True, "Vertical"
assert checkio([
[7, 1, 4, 1],
[1, 2, 5, 2],
[3, 4, 1, 3],
[1, 1, 8, 1]
]) == False, "Nothing here"
assert checkio([
[2, 1, 1, 6, 1],
[1, 3, 2, 1, 1],
[4, 1, 1, 3, 1],
[5, 5, 5, 5, 5],
[1, 1, 3, 1, 1]
]) == True, "Long Horizontal"
assert checkio([
[7, 1, 1, 8, 1, 1],
[1, 1, 7, 3, 1, 5],
[2, 3, 1, 2, 5, 1],
[1, 1, 1, 5, 1, 4],
[4, 6, 5, 1, 3, 1],
[1, 1, 9, 1, 2, 1]
]) == True, "Diagonal"
March 13, 2014
Comments: