Spiral Matrix II
来源:互联网 发布:部落冲突巨人升级数据 编辑:程序博客网 时间:2024/06/11 02:25
Given an integer n, generate a square matrix filled with elements from 1 ton2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
思路:
这个算法跟之前的 Sprial Matrix I,一模一样。
不一样的地方就是按着递增的加数进去就行了。
public class Solution { public int[][] generateMatrix(int n) { int N = Math.abs(n); int num = 1; int[][] matrix = new int[N][N]; int beginX = 0; int endX = N-1; int beginY = 0; int endY = N-1; while(true){ // left to right; for(int col=beginY; col<=endY; col++){ matrix[beginX][col] = num; num++; } if(++beginX>endX) break; //top to bottom; for(int row = beginX; row<=endX; row++){ matrix[row][endY] = num; num++; } if(--endY<beginY) break; //right to left; for(int col = endY; col>=beginY; col--){ matrix[endX][col]=num; num++; } if(--endX<beginX) break; //bottom to top; for(int row = endX; row>=beginX; row--){ matrix[row][beginY]=num; num++; } if(++beginY>endY) break; } return matrix; }}
0 0
- Spiral Matrix && Spiral Matrix II
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix II
- LeetCode : Spiral Matrix II
- Spiral Matrix II
- [LeetCode] Spiral Matrix II
- Spiral Matrix II
- Spiral Matrix II
- [LeetCode]Spiral Matrix II
- Spiral Matrix II
- Spiral Matrix I(II)
- Spiral Matrix II
- [leetcode]Spiral Matrix II
- LeetCode-Spiral Matrix II
- [leetcode] Spiral Matrix II
- LeetCode - Spiral Matrix II
- Spiral Matrix II
- android学习笔记之Fragments
- OpenGL学习一OpenGL学习资源
- OpenGL学习二--基础知识
- android学习之popupWindow
- 又见回文
- Spiral Matrix II
- 在iOS中使用ZXing库
- ArcGIS 无法创建SDE:Failed to setup st_geometry type.
- Android中静态变量的生命周期
- <学习分享>.手势识别
- hdu 1166 敌兵布阵(线段树)
- Sql 递归查询
- 幽默讲解linux的Socket IO模型
- mac安装tomcat