螺旋矩阵II

LeetCode每日一题,59. Spiral Matrix II

先看题目描述

6rOKfJ.png

大意就是给定一个数字 n,生成一个 n × n 的矩阵,元素包括 1 到 n 的平方,且元素按顺时针螺旋排列

算法和思路

按层模拟

还是按层模拟,逐层的填充元素,和昨天的题目基本一样,但这次的代码和昨天实现不一样,用了双指针,看着简洁些

算法源码

按层模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public int[][] generateMatrix(int n) {
int left = 0;
int right = n - 1;
int count = 1;
int[][] ans = new int[n][n];
while (left <= right) {
for (int i = left; i <= right; i++) {
ans[left][i] = count++;
}
for (int i = left + 1; i <= right; i++) {
ans[i][right] = count++;
}
if (left < right) {
for (int i = right - 1; i >= left; i--) {
ans[right][i] = count++;
}
for (int i = right - 1; i > left; i--) {
ans[i][left] = count++;
}
}
left++;
right--;
}
return ans;
}
}