day2_螺旋矩阵II(leetcode59)

本文讲述了如何生成一个包含1到n^2元素,按顺时针螺旋排列的nxn矩阵。作者分享了解决问题的初始思路,暴力解法的尝试过程,以及在实现中处理奇数n和中心值的挑战,最终提供了一个解决方案。
摘要由CSDN通过智能技术生成

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

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

示例 2:

输入:n = 1
输出:[[1]]

讨论:

在尝试解决这个问题时,我最初的想法是寻找一个整体填充每个值的模式,可以通过一些技巧来更新矩阵。然而,我一直没有想出一个巧妙的解决方案。从这个经验可以学到,如果没有一个巧妙的思路,就应该尽可能先使用能想到的暴力解法(brute force)来尝试解决问题,然后再思考可能的优化空间。

在实现过程中,需要特别注意当 n 为奇数时,如何正确处理矩阵中心的值。我在实现中没有正确的处理中心值,并且判断条件也没有正确设置循环终止条件,导致进入了死循环。为了避免这种情况,我们需要多尝试画图测试几个实际的例子,然后总结归纳出具体的实现方法。

When I first attempted to solve this problem, my initial thought was to find a pattern for filling in each value of the matrix as a whole, which could be updated with some tricks. However, I couldn't come up with a clever solution. From this experience, I learned that if I don't have a clever approach in mind, I should try to solve the problem using a brute force method that I can think of, and then consider possible optimizations later.

During the implementation, it's important to pay special attention to how to correctly handle the center value when n is odd. In my initial implementation, I didn't handle the center value correctly and also didn't set the loop termination condition properly, resulting in an infinite loop. To avoid this situation, we need to try several actual examples and then summarize and deduce the specific implementation method.

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        if (n == 1) return { {1} };
        vector<vector<int>> solution(n, vector<int>(n, 0));
        int sqr = n * n, counter = 1;
        int start_x = 0, start_y = 0, end_x = n - 1, end_y = n - 1;
        while (sqr > counter) { // 之前写成了sqr >= counter,没有考虑到n为奇数的情况以及处理boundary的问题,导致infinity loop,不会退出
            for (int i = start_x; i < end_x; i++) {
                solution[start_y][i] = counter++;
            }
            for (int j = start_y; j < end_y; j++) {
                solution[j][end_x] = counter++;
            }
            for (int i = end_x; i > start_x; i--) {
                solution[end_y][i] = counter++;
            }
            for (int j = end_y; j > start_y; j--) {
                solution[j][start_x] = counter++;
            }
            start_x++;
            start_y++;
            end_x--;
            end_y--;
        }
        if (n % 2 == 1) {
            solution[n / 2][n / 2] = n * n;
        }
        return solution;

    }

};

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值