【LeetCode】59. Spiral Matrix II
来源:互联网 发布:股市分析软件 编辑:程序博客网 时间:2024/06/10 01:44
问题描述
https://leetcode.com/problems/spiral-matrix-ii/#/description
Given an integer n
, generate a square matrix filled with elements from 1
to n^2
in spiral order.
For example,
Given n = 3
,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
输入一个数n
,输出从1
到n^2
的螺旋排序矩阵。
算法
直接按照从左到右、从上到下、从右到左、从下到上的顺序一个个数的填充数组即可。
代码
public int[][] generateMatrix(int n) { if(n<=0) return new int[][]{}; int[][] res = new int[n][n]; // 开始填入数字 int rowBegin = 0, rowEnd = n-1; int colBegin = 0, colEnd = n-1; int index = 1; while(rowBegin<=rowEnd || colBegin<=colEnd) { // 从左到右 for(int i=colBegin;i<=colEnd;i++) { res[rowBegin][i] = index++; } rowBegin++; // 从上到下 for(int i=rowBegin;i<=rowEnd;i++) { res[i][colEnd] = index++; } colEnd--; // 从右到左 if(colEnd>=colBegin) { for(int i=colEnd;i>=colBegin;i--) { res[rowEnd][i] = index++; } } rowEnd--; // 从下到上 if(rowEnd >=rowBegin) { for(int i=rowEnd;i>=rowBegin;i--) { res[i][colBegin] = index++; } } colBegin++; } return res; }
LeetCode解题代码仓库:https://github.com/zgljl2012/leetcode-java
阅读全文
1 0
- [LeetCode]59.Spiral Matrix II
- LeetCode --- 59. Spiral Matrix II
- [Leetcode] 59. Spiral Matrix II
- [leetcode] 59.Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- 59. Spiral Matrix II LeetCode
- [leetcode] 59. Spiral Matrix II
- leetcode 59. Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- leetcode 59. Spiral Matrix II
- LeetCode *** 59. Spiral Matrix II
- leetcode 59. Spiral Matrix II
- Leetcode 59. Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- LeetCode - 59. Spiral Matrix II
- [LeetCode] 59. Spiral Matrix II
- [leetcode] 59. Spiral Matrix II
- [leetcode]59. Spiral Matrix II
- 调试解密工具
- 一篇文章让你了解互联网公司的职位架构以及职能
- 关于一些file类的基础代码
- c# 运算符 &&和&有什么区别
- U盘安装Centos7.0 U盘安出现dracut解决办法
- 【LeetCode】59. Spiral Matrix II
- MongoDB C100DEV 认证考试
- Android常用的数据结构
- 求斐波那契(Fibonacci)数列通项的七种实现方法
- 牛腩新闻错误总结
- python + Mongodb小试
- [LeetCode
- backtrace 调试 代码执行的路径(调用栈)
- python~crush之convert工具