螺旋矩阵II
2024-10-08 16:40:23
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;
}
最新文章
- android native crash 分析
- Arduino101/Genuino101的安装入门
- select元素javascript常用操作 转
- 8611&#160;大牛之路I
- sencha cmd 更新日志
- 告别node-forever,拥抱PM2
- android学习日记28--Android中常用设计模式总结
- Dirichlet Process 和 Dirichlet Process Mixture模型
- Linux 基础入门----推荐课程
- Maven创建项目: Failed to execute goal org.apache.maven.plugin( mvn archetype:create)
- 【jquery、XML】jquery通过按钮使打开select
- unity3d和php后台简单交互--一
- url传参后获取参数
- mybatis-java代码调用部分
- 二叉树——遍历篇(递归/非递归,C++)
- Create an Azure SQL database in the Azure portal
- Confluence 6 ";net.sf.hibernate.PropertyValueException: not-null"; 相关问题解决
- python实现http get请求
- API Gateway : Kong
- PHP代码审计笔记--任意文件上传