LeetCode | 59 SpiralMatrixII

主类

https://github.com/dolphinmind/datastructure/tree/datastructure-array-02

循环不变量原则, 保证问题边界的逻辑一致性(从二分法的启发)

  • 初始位置
  • 旋转圈数 奇偶性判断:每旋转一圈,都要减少两个行列(绘图看一下,就这么简单理解,对于N为奇数,最后只剩下一个中心位置,独立判断)
  • 四条边的边界逻辑
  • offset

这是一个过程测试的代码,主要用于自己的程序检验

package com.github.dolphinmind.array;

/**
 * @author dolphinmind
 * @ClassName SpiralMatrixII
 * @description 59 . 螺旋矩阵 II
 * @date 2024/8/1
 */

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

        if (n == 0) {
            return null;
        }

        int[][] nums = new int[n][n];

        int loop = 1;

        int startX = 0;
        int startY = 0;

        int moveX  = 0;
        int moveY  = 0;

        int offset = 1;
        int count  = 1;

        while (loop <= n/2) {
            System.out.println("上边");
            while (moveY < n - offset) {
                printPoint(moveX, moveY, count);
                nums[moveX][moveY] = count++;
                moveY++;
            }
            System.out.println("右边");
            while (moveX < n - offset) {
                printPoint(moveX, moveY, count);

                nums[moveX][moveY] = count++;
                moveX++;
            }

            System.out.println("下边");
            while (moveY > startY) {
                printPoint(moveX, moveY, count);

                nums[moveX][moveY] = count++;
                moveY--;
            }

            System.out.println("左边");
            while (moveX > startX) {
                printPoint(moveX, moveY, count);

                nums[moveX][moveY] = count++;
                moveX--;
            }

            startX++;
            startY++;
            loop++;
            offset++;

            moveX = startX;
            moveY = startY;
        }

        if ( n % 2 == 1) {
            System.out.println("中心");
            printPoint(startX, startY, count);
            nums[startX][startY] = count;
        }

        return nums;
    }

    public void printPoint(int x, int y, int count) {
        System.out.println("[" + x + "," + y + "] = " + count);
    }
}

测试类

package com.github.dolphinmind.array;

import org.junit.Test;

/**
 * @author dolphinmind
 * @ClassName SpiralMatrixIITest
 * @description
 * @date 2024/8/1
 */

public class SpiralMatrixIITest {

    @Test
    public void generateMatrix() {
        int[][] matrix = new SpiralMatrixII().generateMatrix(4);

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }

}

posted @ 2024-08-01 23:12  Neking  阅读(21)  评论(0编辑  收藏  举报