LeetCode常见面试题练习 59. 螺旋矩阵 II

题目表述:

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

 解题思路:

如上图,顺时针顺序螺旋排列,探索方向分四个方向,x正方向,y正方向,y负方向,x负方向(x正方形在前,其他顺序不是很重要)。

先按x正方形走,填充1,2,3,4,5判断到了边界,则按上诉四个方向尝试探索,x正方形已经有填充值4不能走,y正方形可以走;

按y正方形走,填充6,7,8,9到边界,继续四个方向尝试探索,x正方形超出边界,y正方形超出边界,y负方向有8了不能走,x负方向可以走;

按x负方向走,填充10,11,12,13,只能延y负方向走,一直如此探索下去,直到没有可以走的方向为止。

 

代码:

class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        move = [[0,1],[1,0],[-1,0],[0,-1]]
        import numpy as np
        arr = np.ones([n,n]) * -1
        def is_edge(i,j,arr,item):
            # 是不是边界,或者已经访问过的
            if i + item[0] >= 0 and i + item[0] < n and j + item[1] >= 0 and j + item[1] < n and arr[
                i + item[0]][j + item[1]] == -1:
                return False
            return True
        # 获取一个可以走的方向,如果没有返回None
        def get_dir(i,j,arr):
            for item in move:
                if not is_edge(i,j,arr,item):
                    return item
            return None
        i,j=0,0
        arr[i][j]=1
        now_n = 2
        while True:
            direction = get_dir(i,j,arr)
            if not direction: # 没有可走的方向了,结束探索
                break
            isStop = False
            while not isStop: # 沿着一个方向一直探索,知道边界
                i += direction[0]
                j += direction[1]
                arr[i][j]=now_n
                now_n+=1
                if is_edge(i,j,arr,direction):
                    isStop = True
        return np.asarray(arr,dtype=int)
if __name__ == '__main__':
    s = Solution()
    r = s.generateMatrix(5)
    print(r)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值