题目说明
给你一个正整数 n ,生成一个包含 1 到 n² 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例
例1

1 2
| 输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]
|
例2
笔者理解
此题是一道数组算法问题,在力扣题库中被定义为中等题。
解法
当笔者阅读完此题后,发现此题与昨天的螺旋矩阵思路大概一致,就是像在格子上走路,我们只需要预先规划好格子,然后在即将走出边界和面对已经走过的格子时,调转方向即可。让我们来看看具体如何实现的吧。
实现
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| public int[][] generateMatrix(int n) { int []direX = { 0, 1, 0, -1 }; int []direY = { 1, 0, -1, 0 };
boolean [][]tick = new boolean[n][n];
for(int i = 0; i < tick.length; i++) { Arrays.fill(tick[i],false); }
int[][] result = new int[n][n];
int times = 1; int x = 0; int y = 0;
int dire = 0;
while(times <= n * n){ result[x][y] = times; tick[x][y] = true;
x += direX[dire]; y += direY[dire];
if(x*y < 0 || (n - x) * (n - y) <= 0 || tick[x][y]) {
x -= direX[dire]; y -= direY[dire]; dire = (dire + 1) % 4; x += direX[dire]; y += direY[dire]; } times++; } return result; }
|
时间和空间效率都还行,可见此解法还比较适合此题;

总结
本题是今天的每日一题,难度是为中等,感兴趣的朋友都可以去尝试一下,此题还有其他更多的解法,朋友们可以自己逐一尝试。