LeetCode 059 Spiral Matrix II
2015-11-22 11:36
302 查看
题目描述
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
代码
[code] public static int[][] generateMatrix(int n) { if (n <= 0) { return new int[0][0]; } int[][] matrix = new int ; int num = 1; int startx = 0, endx = n - 1; int starty = 0, endy = n - 1; while (startx <= endx && starty <= endy) { for (int y = starty; y <= endy; y++) { matrix[startx][y] = num++; } for (int x = startx + 1; x <= endx; x++) { matrix[x][endy] = num++; } if (startx == endx || starty == endy) { break; } for (int y = endy - 1; y >= starty; y--) { matrix[endx][y] = num++; } for (int x = endx - 1; x >= startx + 1; x--) { matrix[x][starty] = num++; } startx++; starty++; endx--; endy--; } return matrix; }
相关文章推荐
- 使APP消除上方手机消息提示栏(显示WIFI,信号格那栏)消失的方法
- 九度oj-1511-从尾到头打印链表
- UML中的四种关系
- Go 语言变量
- URAL 1225 递推
- Go 语言数据类型
- Hadoop伪分布式搭建
- 什么是 "asmlinkage"
- 回表
- QT:数据库总结(三)之SQL模型类-QSqlTableModel模型
- Android实战之你应该使用哪个网络库?
- Go 语言基础语法
- 特殊回文数
- rk3288_android5.1__android4.4 jdk1.6和jdk1.7共存问题 ubuntu java7 The required version is: "1.7.x"
- Go 语言结构
- springMvc实现
- 点击button事件和拖动button事件冲突
- 第一次撰写个人网站的一点技术总结
- Go 语言环境安装
- iOS完整学习路线图