LeetCode-59-螺旋矩阵 II


题意描述:

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


示例:

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

解题思路:

Alice: 我明白了,😎,LeetCode里面题目后面加了一个 II 的并不意味这 要比原来的题目难。
Bob: 哈哈哈,也许就像这题一样,这是换汤不换药而已。
Alice: 那个图再贴一下吧。
在这里插入图片描述
Bob: 好的。😎


代码:

Python 方法一:

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:

        i = 0;
        j = -1;
        idxs = -1
        clos = n
        rows = n
        cnt = 1
        tot = n*n
        ans = [[0 for x in range(n)] for z in range(n)]
        directions = [[0,1], [1,0], [0, -1], [-1, 0]]

        while cnt <= tot:

            idxs = (idxs + 1) % 4
            for x in range(clos):
                i += directions[idxs][0]
                j += directions[idxs][1]
                ans[i][j] = cnt
                cnt += 1
            rows -= 1

            idxs = (idxs + 1) % 4
            for x in range(rows):
                i += directions[idxs][0]
                j += directions[idxs][1]
                ans[i][j] = cnt
                cnt += 1
            clos -= 1

        return ans

Java 方法一: 螺旋访问数组,填充元素。

class Solution {
    public int[][] generateMatrix(int n) {

        int[][] ans = new int[n][n];
        int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
        int i = 0;
        int j = -1;
        // 二维数组的下标
        int idx = -1;
        // directions 数组的下标
        int cnt = 1;
        int tot = n * n;
        int cols = n;
        int rows = n;

        while(cnt <= tot){

            // 横向
            idx = (idx+1) % 4;
            for(int x=0; x<cols; ++x){
                i += directions[idx][0];
                j += directions[idx][1];
                ans[i][j] = cnt;
                cnt += 1;
            }
            rows -= 1;

			// 纵向
            idx = (idx + 1) % 4;
            for(int x=0; x<rows; ++x){
                i += directions[idx][0];
                j += directions[idx][1];
                ans[i][j] = cnt;
                cnt += 1;
            }
            cols -= 1;
        }

        return ans;
    }
}

易错点:

  • 一些测试用例:
1
2
3
4
  • 答案:
[[1]]
[[1,2],[4,3]]
[[1,2,3],[8,9,4],[7,6,5]]
[[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]

总结:

在这里插入图片描述


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值