原题
https://leetcode-cn.com/problems/spiral-matrix-ii/

思路
while循环,定义4个变量
最左列:left
最右列:right
最上行:top
最下行:bottom
每次循环 ➡️ ⬇️ ⬅️ ⬆️
循环完 left++ right-- top++ bottom–
题解
package com.leetcode.code;
/**
* @ClassName Code59
* @Author ZK
* @Description
* @Date 2021/2/4 10:18
* @Version 1.0
**/
public class Code59 {
public static void main(String[] args) {
int[][] res = generateMatrix(3);
for (int i = 0; i < res.length; i++) {
for (int j = 0; j < res[i].length; j++) {
System.out.print(res[i][j] + "\t");
}
System.out.println();
}
}
public static int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int count = 1;
int left = 0;
int right = n-1;
int top = 0;
int bottom = n-1;
while(left <= right && top <= bottom){
// 右
for (int i = left; i <= right; i++) {
res[top][i] = count++;
}
// 下
for (int i = top+1; i <= bottom; i++) {
res[i][right] = count++;
}
// 左
for (int i = right-1; i >= left; i--) {
res[bottom][i] = count++;
}
// 上
for (int i = bottom-1; i >= top+1; i--) {
res[i][left] = count++;
}
left++;
right--;
top++;
bottom--;
}
return res;
}
}
这是一个关于LeetCode中螺旋矩阵II问题的解决方案。代码采用while循环,通过定义四个变量来跟踪矩阵的边界,然后按照右、下、左、上的顺序填充数值。循环结束后更新边界,直至完成矩阵填充。该算法实现了一个生成指定大小螺旋矩阵的功能。
649

被折叠的 条评论
为什么被折叠?



