welcome to my blog
LeetCode Top Interview Questions 59. Spiral Matrix II (Java版; Medium)
题目描述
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
第一次做; 和剑指29题的顺时针打印很像, 核心: 1)确定圈数, 2)确定每圈打印的起点及剩余三个顶点的坐标
/* 核心: 模拟螺旋的过程; 确定好打印几圈? 每一圈的打印起点? */
class Solution {
public int[][] generateMatrix(int n) {
int[][] arr = new int[n][n];
//打印几圈
int loops = (n+1)/2;
int num = 1;
for(int i=0; i<loops; i++){
//每一圈打印的起点(i,i)
//左到右; i-0 = n-1-y -> y=n-1-i
for(int col=i; col<=n-1-i; col++){
arr[i][col] = num++;
}
//上到下, 上开下闭; i-0=n-1-ROW -> ROW=n-1-i
for(int row=i+1; row<=n-1-i; row++){
arr[row][n-1-i] = num++;
}
//右到左, 右开左闭; n-1-col = COL-0 -> COL=i
for(int col=n-1-i-1; col>=i; col--){
//n-1-row = i-0
arr[n-1-i][col] = num++;
}
//下到上, 下开上开; n-1-row=i-0 -> row=n-1-i
for(int row=n-1-i-1 ; row>i; row--){
arr[row][i] = num++;
}
}
return arr;
}
}
力扣优秀题解

class Solution {
public int[][] generateMatrix(int n) {
int l = 0, r = n - 1, t = 0, b = n - 1;
int[][] mat = new int[n][n];
int num = 1, tar = n * n;
while(num <= tar){
for(int i = l; i <= r; i++) mat[t][i] = num++; // left to right.
t++;
for(int i = t; i <= b; i++) mat[i][r] = num++; // top to bottom.
r--;
for(int i = r; i >= l; i--) mat[b][i] = num++; // right to left.
b--;
for(int i = b; i >= t; i--) mat[i][l] = num++; // bottom to top.
l++;
}
return mat;
}
}
还没有评论,来说两句吧...