螺旋矩阵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;
}
總結
- 上一篇: 免费网络学术资源获取
- 下一篇: label smoothing(标签平滑