Last active
June 23, 2021 15:05
-
-
Save djaquels/8d42e7bc8977de7e22c8101b93089e29 to your computer and use it in GitHub Desktop.
Spiral Matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def spiralPathMatrix(matrix, n, m): | |
# right down left up | |
directions = [1,0,0,0] | |
verticalLimit = 0 | |
horizontalLimit = 0 | |
iterations = (n * m ) | |
row,col = [0,0] | |
direction = 0 # we moving right | |
prev = 0 | |
items = [matrix[0][0]] | |
while(len(items) < iterations): | |
row = row + (directions[1]) -(directions[3]) | |
col = col + (directions[0]) - (directions[2]) | |
if col % (m-horizontalLimit) == 0 and direction == 0: | |
directions[prev] = 0 | |
direction = (direction + 1) % 4 | |
prev = direction | |
directions[direction] = 1 | |
col -= 1 | |
continue | |
if col == horizontalLimit and direction == 2: | |
directions[prev] = 0 | |
direction = (direction + 1) % 4 | |
prev = direction | |
directions[direction] = 1 | |
horizontalLimit += 1 | |
if row % (n-verticalLimit) == 0 and direction == 1: | |
directions[prev] = 0 | |
direction = (direction + 1) % 4 | |
prev = direction | |
directions[direction] = 1 | |
row -=1 | |
continue | |
if row == verticalLimit and direction == 3: | |
directions[prev] = 0 | |
direction = (direction + 1) % 4 | |
prev = direction | |
directions[direction] = 1 | |
verticalLimit += 1 | |
row += 1 | |
continue | |
items.append(matrix[row][col]) | |
return items | |
n = 3 | |
m = 3 | |
grid = [[-41, 334, 169], | |
[478, 962, -705], | |
[-281, -961, 995]] | |
print(spiralPathMatrix(grid,n,m)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment