題目信息
給你一個正整數(shù) n ,生成一個包含 1 到 n2 所有元素,且元素按順時針順序螺旋排列的 n x n 正方形矩陣 matrix 。
示例1:
matrix3_3.jpg
輸入:n = 3
輸出:[[1,2,3],[8,9,4],[7,6,5]]
解題思路
- 暴力破解:
- 無效操作分析:
- 優(yōu)化方法:
- 考慮邊界
- 編碼實(shí)現(xiàn)
代碼
class Solution {
public int[][] generateMatrix(int n) {
if (n <= 0) {
return new int[1][1];
}
int maxNum = n * n;
int[][] matrix = new int[n][n];
int row = 0, column = 0;
// 定義方向矩陣
int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // 右下左上
int directionIndex = 0;
for (int curNum = 1; curNum <= maxNum; curNum++) {
matrix[row][column] = curNum;
// 計算下一個橫縱坐標(biāo)
int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
// 判斷坐標(biāo)的合法性和當(dāng)前位置是否已經(jīng)賦值
if (nextRow < 0 || nextRow >= n || nextColumn < 0 || nextColumn >= n || matrix[nextRow][nextColumn] != 0) {
directionIndex = (directionIndex + 1) % 4; // 順時針旋轉(zhuǎn)至下一個方向
}
row = row + directions[directionIndex][0];
column = column + directions[directionIndex][1];
}
return matrix;
}
}
題目來源:力扣(LeetCode)
題目鏈接:https://leetcode-cn.com/problems/spiral-matrix-ii
商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。