日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

螺旋矩阵II

發布時間:2024/10/8 编程问答 40 如意码农
生活随笔 收集整理的這篇文章主要介紹了 螺旋矩阵II 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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 ]
]

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/spiral-matrix-ii
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

建立top,bottom,left,right四個邊界,創建n*n二維數組并逆時針賦值,當到達邊界時,上、左邊界自增,右、下邊界自減,當top>bottom或left>right時,結束循環。代碼如下:

    public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int top = 0;
int bottom = n-1;
int left = 0;
int right = n-1;
int target = 1;
//看了一下題解,有的大佬把判斷循環是否結束的語句設置為target<=n*n
while(top <= bottom || left <= right)
{
//從左往右
for(int i = left; i <= right; i++)
{
res[top][i] = target++;
}
top++;
//從上往下
for(int i = top; i <= bottom; i++)
{
res[i][right] = target++;
}
right--;
//從右往左
for(int i = right; i >= left; i--)
{
res[bottom][i] = target++;
}
bottom--;
//從下往上
for(int i = bottom; i >= top; i--)
{
res[i][left] = target++;
}
left++; }
return res;
}

總結

以上是生活随笔為你收集整理的螺旋矩阵II的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。