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;
}

最新文章

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

热门文章

  1. Chrome插件开发(二)
  2. windows vscode 远程调试代码
  3. 蓝牙耳机没声音,用mac平台下的safari时
  4. 腾讯新闻构建高性能的 react 同构直出方案
  5. python学习之【第六篇】:Python中的字典及其所具有的方法
  6. sshd服务及基于密钥远程登陆(无需密码)
  7. Android9.0 SystemUI 网络信号栏定制修改
  8. Android常见内存泄露
  9. 关于Eratosthenes筛子算法筛选小于n的素数的理解
  10. 《计算机网络 自顶向下方法》 第2章 应用层 Part2