執行結果:
通過
顯示詳情
執行用時 :0 ms, 在所有 Java 提交中擊敗了100.00% 的用戶
內存消耗 :37.5 MB, 在所有 Java 提交中擊敗了5.09%的用戶
題目:
給定一個正整數 n,生成一個包含 1 到 n2 所有元素,且元素按順時針順序螺旋排列的正方形矩陣。
示例:
輸入: 3
輸出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/spiral-matrix-ii
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路:
和螺旋矩陣I很像,但是要比它簡單,沒有那麼多特殊情況。
代碼:
class Solution {
public int[][] generateMatrix(int n) {
int[][] result=new int[n][n];
int row1=0;
int row2=n-1;
int col1=0;
int col2=n-1;
int count=1;
while(count<=n*n)
{
for(int i=col1;i<=col2;i++)
{
result[row1][i]=count++;
}
for(int i=row1+1;i<=row2;i++)
{
result[i][col2]=count++;
}
for(int i=col2-1;i>=col1;i--)
{
result[row2][i]=count++;
}
for(int i=row2-1;i>row1;i--)
{
result[i][col1]=count++;
}
col1++;col2--;row1++;row2--;
}
return result;
}
}