首页 > 试题广场 >

螺旋矩阵

[编程题]螺旋矩阵
  • 热度指数:139185 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。

数据范围:,矩阵中任意元素都满足
要求:空间复杂度 ,时间复杂度
示例1

输入

[[1,2,3],[4,5,6],[7,8,9]]

输出

[1,2,3,6,9,8,7,4,5]
示例2

输入

[]

输出

[]
class Solution:
    def spiralOrder(self , matrix: List[List[int]]) -> List[int]:
        # write code here
        def check_next(i, j, d):
            # 确定下一步是否能按原方向走
            if directions[d] == 'r':
                j += 1 
            elif directions[d] == 'd':
                i += 1 
            elif directions[d] == 'l':
                j -= 1 
            elif directions[d] == 'u':
                i -= 1 
            if i <= m-1 and j <= n-1 and matrix[i][j] != 1000:
                return True 
            else:
                return False

        # base case 
        if len(matrix) == 0:
            return []
        res = []
        directions = ['r', 'd', 'l', 'u']
        d = 0
        m, n = len(matrix), len(matrix[0])
        count = 0 
        i, j = 0, 0
        while count < m*n:
            res.append(matrix[i][j])
            # 标记已走过的
            matrix[i][j] = 1000
            # 更新计数
            count += 1
            # 确定下一步是否能按原方向走
            if check_next(i, j, d) == False:
                d += 1 
                d %= 4
            # 确定下一步的方向
            if directions[d] == 'r':
                j += 1 
            elif directions[d] == 'd':
                i += 1 
            elif directions[d] == 'l':
                j -= 1 
            elif directions[d] == 'u':
                i -= 1 
        return res
发表于 2023-04-26 07:01:26 回复(0)
和官方题解差不多
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param matrix int整型二维数组 
# @return int整型一维数组
#
class Solution:
    def spiralOrder(self , matrix: List[List[int]]) -> List[int]:
        # write code here
        if matrix == []:
            return []
        m,n = len(matrix),len(matrix[0])
        up,down = 0,m-1
        left,right = 0,n-1
        res = []
        while left<=right and up<=down:
            for i in range(left,right+1):
                res.append(matrix[up][i])
            up += 1
            if up > down:
                break
            
            for i in range(up,down+1):
                res.append(matrix[i][right])
            right -= 1
            if right < left:
                break

            for i in range(right,left-1,-1):
                res.append(matrix[down][i])
            down -= 1
            if up > down:
                break
            
            for i in range(down,up-1,-1):
                res.append(matrix[i][left])
            left += 1
            if left > right:
                break
        
        return res


发表于 2023-03-24 16:53:35 回复(0)
class Solution:
    def spiralOrder(self , matrix: List[List[int]]) -> List[int]:
        # write code here
        n=len(matrix)
        box1=[]
        if n==0:
            return matrix
        if len(matrix[0])==1:
            for i in matrix:
                for j in i:
                    box1.append(j)
            return box1                
        box=[]
        def xunhuna(res,box):
            n=len(res)
            m=len(res[0])
            if n==2:
                a=res[0]
                for i in a:
                    box.append(i)
                b=res[1]
                for i in range(1, len(b) + 1):
                    box.append(b[-i])
            elif n==1:
                a = res[0]
                for i in a:
                    box.append(i)
            elif n>2 and m>=2:
                a=res.pop(0)
                b=res.pop(-1)
                for i in a:
                    box.append(i)
                for i in range(len(res)):
                    x=res[i].pop(len(res[i])-1)
                    box.append(x)
                    # box.append(res[i][len(res[i]) - 1])
                for i in range(1, len(b) + 1):
                    box.append(b[-i])

                for i in range(1,len(res)+1):
                    box.append(res[-i][0])
                    x = res[-i].pop(0)
                if len(res)>0:
                    xunhuna(res,box)
              
            return box
        return xunhuna(matrix,box)

发表于 2022-11-27 14:11:05 回复(0)
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param matrix int整型二维数组 
# @return int整型一维数组
#
class Solution:
    def spiralOrder(self , matrix: List[List[int]]) -> List[int]:
        ret = []
        m, n = len(matrix), 0
        if m > 0:
            n = len(matrix[0])
        x1, x2, y1, y2 = 0, n, 0, m
        while x1 < x2 and y1 < y2:
            for i in range(x1, x2):
                ret.append(matrix[y1][i])
            y1 = y1 + 1
            if y1 >= y2:
                break
            for j in range(y1, y2):
                ret.append(matrix[j][x2 - 1])
            x2 = x2 - 1
            if x1 >= x2:
                break
            for i in range(x2 - 1, x1 - 1, -1):
                ret.append(matrix[y2 - 1][i])
            y2 = y2 - 1
            if y1 >= y2:
                break
            for j in range(y2 - 1, y1 -1, -1):
                ret.append(matrix[j][x1])
            x1 = x1 + 1
        return ret

发表于 2022-09-17 12:13:38 回复(0)
    class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res=[]
        if len(matrix)==0:
            return []
        #定义四个边界点
        left=0
        right=len(matrix[0])-1
        top=0
        bottom=len(matrix)-1
        #在不超过边界的条件下,进行一轮循环
        while (top<bottom and left<right):
            for i in range(left,right):
                res.append(matrix[top][i])
            for i in range(top,bottom):
                res.append(matrix[i][right])
            for i in range(right,left,-1):
                res.append(matrix[bottom][i])
            for i in range(bottom,top,-1):
                res.append(matrix[i][left])
            left+=1
            top+=1
            right-=1
            bottom-=1
        
        #如果剩余1行或1列:left=0 right1
        if top==bottom:
            for i in range(left,right+1):
                res.append(matrix[top][i])
        elif left==right:
            for i in range(top,bottom+1):
                res.append(matrix[i][left])
        return res


发表于 2022-01-18 20:24:50 回复(0)
class Solution:
    def spiralOrder(self , matrix: List[List[int]]) -> List[int]:
        
        if not matrix:
            return []
        
        def circle_one(a,b,length,weight):
            res=[]
            if length==1:
                if weight==1:
                    res.append(matrix[a][b])
                    return res
                else:
                    for i in range(a,weight+a):
                        res.append(matrix[i][length+b-1])
                    return res
            else:
                for j in range(b,length+b-1):
                    res.append(matrix[a][j])
                if weight==1:
                    res.append(matrix[a][length+b-1])
                    return res
                else:
                    for i in range(a,weight+a-1):
                        res.append(matrix[i][length+b-1])
                    for j in range(length+b-1,b,-1):
                        res.append(matrix[weight+a-1][j])
                    for i in range(weight+a-1,a,-1):
                        res.append(matrix[i][b])
                    return res
        length=len(matrix[0])
        weight=len(matrix)
        result=[]
        a=-1
        b=-1
        while length>0 and weight>0:
            a+=1
            b+=1
            res=circle_one(a,b,length,weight)
            result.extend(res)
            length=length-2
            weight=weight-2
             
        return  result
            

发表于 2021-12-30 02:30:55 回复(0)
class Solution:
    def spiralOrder(self , matrix: List[List[int]]) -> List[int]:
        if not matrix&nbs***bsp;not matrix[0]: return []
        M, N = len(matrix), len(matrix[0])
        #up, down, left, right 分别表示四个方向的边界
        left, right, up, down = 0, N - 1, 0, M - 1
        res = []
        x, y = 0, 0
        dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
        #cur_d 表示当前的移动方向的下标,dirs[cur_d] 就是下一个方向需要怎么修改 x, y
        cur_d = 0
        while len(res) != M * N:
            res.append(matrix[x][y])
            if cur_d == 0 and y == right:#右→
                cur_d += 1
                up += 1#上边界+1
            elif cur_d == 1 and x == down:#下↓
                cur_d += 1
                right -= 1#右边界-1
            elif cur_d == 2 and y == left:#左←
                cur_d += 1
                down -= 1#下边界-1
            elif cur_d == 3 and x == up:#上↑
                cur_d += 1
                left += 1#左边界+1
            cur_d %= 4
            x += dirs[cur_d][0]
            y += dirs[cur_d][1]
        return res

发表于 2021-11-13 17:45:22 回复(0)
难点在于分析每个角落转向的规律,画个5*3图就明了了,i,j,i为行,j为列,m,n为行数和列数还要考虑空的情况(坑)
左上:原本是up走向,且要有i-j = 1,顺时针转90度,变成right
右上:原本是right走向,且要有i+j = n-1,顺时针转90度,变成right
右下:原本是down走向,且要有m-i = n-j,实际上就是下标【-1,-1】,【-2,-2】这种,顺时针转90度,变成right
左下:原本是left走线和,且要有i+j = m-1,顺时针转90度,变成right
class Solution:
    def spiralOrder(self,matrix):
        # write code here
        num = 1#记录走过的位置的数量
        i = 0
        j = 0
        way = 1#1right,2down,3left,4up,用来标志此时车车往哪个方向走
        m = len(matrix)
        if(m == 0):
            n = 0
        else:
            n = len(matrix[0])
        save = []
        while(num<=m*n):
            save.append(matrix[i][j])
            if(way == 1 and (i+j == n-1)):#right to down
                way = 2
            elif(way == 2 and m-i == n-j):#down to left
                way = 3
            elif(way == 3 and i+j == m-1):#left to up
                way = 4
            elif(way == 4 and i-j == 1):#up to right
                way = 1

            if(way == 1):
                j += 1
            elif(way == 2):
                i += 1
            elif(way == 3):
                j -= 1
            elif(way == 4):
                i -= 1
            num += 1
        return save



发表于 2021-09-02 23:05:41 回复(0)
# @param matrix int整型二维数组 
# @return int整型一维数组
#
class Solution:
    def spiralOrder(self , matrix ):
        # write code here
        m = len(matrix)
        n = len(matrix[0])
        p = []
        while m > 1 and n > 1:
            for i_t in range(n-1):
                p.append(matrix[0][i_t])
            for i_r in range(m-1):
                p.append(matrix[i_r][-1])
            for i_d in range(n-1):
                p.append(matrix[-1][n-1-i_d])
            for i_l in range(m-1):
                p.append(matrix[m-1-i_l][0])
            for j in range(m):
                del matrix[j][0]
                del matrix[j][-1]
            del matrix[0]
            del matrix[-1]
            m = m-2
            n = n-2
        if m == 1 and n != 1:
            p.extend(matrix)
        if n == 1 and m != 1:
            for j in range(m):
                p.append(matrix[j][0])
        if m == 1 and n==1:
            p.append(matrix[0][0])
        return p

发表于 2021-08-31 15:57:18 回复(0)
呜呜呜,这道题做了好久。
class Solution:
    def spiralOrder(self , matrix ):
        out = []
        if matrix==[]:
            return out
        row = len(matrix)
        colum = len(matrix[0])
        out += self.waiwei(matrix)   # 提取外围数据
        while row>2 and colum>2:
            # 取内部数据
            new_mat = []
            for r in range(1,row-1):
                new_row = []
                for c in range(1,colum-1):
                    new_row.append(matrix[r][c])
                new_mat.append(new_row)
            if matrix==[]:
                return out
            matrix = new_mat
            row = len(matrix)
            colum = len(matrix[0])
            out += self.waiwei(matrix)   # 提取外围数据
        return out
                       
    def waiwei(self , mat):
        li = []
        if mat==[]:
            return li
        row = len(mat)
        colum = len(mat[0])
        for c in range(colum):   # 第一行
            li.append(mat[0][c])
        if row>1:   # 最后一列
            for r in range(1,row):
                li.append(mat[r][-1])
            if colum>1:
                for c in range(1,colum):   # 最后一行
                    li.append(mat[-1][-c-1])
                if row>2:
                    for r in range(1,row-1):   # 第一列
                        li.append(mat[-r-1][0])
        return li


发表于 2021-08-15 20:19:44 回复(0)

问题信息

难度:
12条回答 24306浏览

热门推荐

通过挑战的用户