Wednesday, April 16, 2014

Leetcode (python): Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

Solution:


class Solution:
    # @return a list of lists of integer
    def generateMatrix(self, n):
        matrix=[];
        for i in range(0,n):
            matrix.append([])
            for j in range(0,n):
                matrix[i].append(0)
        
        direction = "right"
        row = 0
        col = 0
        for count in range(1,n*n+1):
            matrix[row][col] = count
            if direction == "right":
                col = col + 1;
                if col >= n-1 or matrix[row][col+1] != 0:
                    direction = "down"
            elif direction == "down":
                row = row + 1;
                if row >= n-1 or matrix[row+1][col] != 0:
                    direction = "left"
            elif direction == "left":
                col = col - 1;
                if col <= 0 or matrix[row][col-1] != 0:
                    direction = "up"
            elif direction == "up":
                row = row - 1;
                if row <= 0 or matrix[row-1][col] != 0:
                    direction = "right"
        return matrix

No comments :

Post a Comment