Simple + Easy to Read Python Solution, 29ms

  • 0

    The idea is to loop the matrix in layers, and in a spiral way. Similar to the common approach for solving the rotate-matrix problem. Used xrange to print in reverse order the bottom row and left column (remember, xrange(z,a,-1) prints from z to a+1 )

        num_rows = len(matrix)
        if num_rows == 0:
            return []
        num_cols = len(matrix[0])
        num_layers = min((num_rows+1) / 2, (num_cols+1) / 2)   
        vals  = []
        for j in range(num_layers):
            for i in range(j, num_cols-j): #print top row
            if j+1 >= num_rows - j: #no column to go through: break
            for i in range(j+1, num_rows-j): #print right column
            if num_cols - j - 1 == j: #no row to go through : break
            for i in xrange(num_cols-j-2, j-1, -1):   #print bottom row             
                vals.append(matrix[num_rows - j - 1][i])
            for i in xrange(num_rows - j - 2, j, -1): #print left column
        return vals

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.