|
| 1 | +# Spiral Matrix |
| 2 | +# https://leetcode.com/problems/spiral-matrix/ |
| 3 | + |
| 4 | +class Boundries(object): |
| 5 | + def __init__(self): |
| 6 | + self.rowStart = None |
| 7 | + self.rowEnd = None |
| 8 | + self.colStart = None |
| 9 | + self.colEnd = None |
| 10 | + |
| 11 | +class Solution(object): |
| 12 | + |
| 13 | + # shrink boundries of the matrix for spiral print. |
| 14 | + def setBoundries(self, matrix, decreaseBy): |
| 15 | + boundries = Boundries() |
| 16 | + # set row boundry |
| 17 | + boundries.rowStart = 0 + decreaseBy |
| 18 | + boundries.rowEnd = len(matrix) - decreaseBy |
| 19 | + # set column boundry |
| 20 | + boundries.colStart = 0 + decreaseBy |
| 21 | + boundries.colEnd = len(matrix[0]) - decreaseBy |
| 22 | + return boundries |
| 23 | + |
| 24 | + def markCellVisitedAddToSpiralPrint(self, matrix, row, col, spiralPrint): |
| 25 | + # if the cell has not been visited |
| 26 | + if (matrix[row][col] != "visited"): |
| 27 | + spiralPrint.append(matrix[row][col]) |
| 28 | + # mark the cell visited |
| 29 | + matrix[row][col] = "visited" |
| 30 | + |
| 31 | + def printSpiral(self, matrix, boundries, spiralPrint): |
| 32 | + # print first row |
| 33 | + for col in range(boundries.colStart, boundries.colEnd): |
| 34 | + self.markCellVisitedAddToSpiralPrint(matrix, boundries.rowStart, col, spiralPrint) |
| 35 | + # print last col |
| 36 | + for row in range(boundries.rowStart+1, boundries.rowEnd-1): |
| 37 | + self.markCellVisitedAddToSpiralPrint(matrix, row, boundries.colEnd-1, spiralPrint) |
| 38 | + # print last row in reverse |
| 39 | + for col in range(boundries.colEnd-1, boundries.colStart-1, -1): |
| 40 | + self.markCellVisitedAddToSpiralPrint(matrix, boundries.rowEnd-1, col, spiralPrint) |
| 41 | + # print first col |
| 42 | + for row in range(boundries.rowEnd-2, boundries.rowStart, -1): |
| 43 | + self.markCellVisitedAddToSpiralPrint(matrix, row, boundries.colStart, spiralPrint) |
| 44 | + |
| 45 | + def spiralOrder(self, matrix): |
| 46 | + spiralPrint = [] |
| 47 | + boundryIndex = 0 |
| 48 | + boundries = self.setBoundries(matrix, boundryIndex) |
| 49 | + # shirnk boundries until bounds are equal. |
| 50 | + while(boundries.rowStart < boundries.rowEnd and boundries.colStart < boundries.colEnd): |
| 51 | + boundryIndex = boundryIndex + 1 |
| 52 | + self.printSpiral(matrix, boundries, spiralPrint) |
| 53 | + boundries = self.setBoundries(matrix, boundryIndex) |
| 54 | + return spiralPrint |
| 55 | + """ |
| 56 | + :type matrix: List[List[int]] |
| 57 | + :rtype: List[int] |
| 58 | + """ |
| 59 | + |
0 commit comments