主类
https://github.com/dolphinmind/datastructure/tree/datastructure-array-02
循环不变量原则, 保证问题边界的逻辑一致性(从二分法的启发)
- 初始位置
- 旋转圈数 奇偶性
- 四条边的边界逻辑
- 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();
}
}
}
标签:count,startX,59,moveY,int,moveX,++,SpiralMatrixII,LeetCode
From: https://www.cnblogs.com/dolphinmind/p/18337771