lintcode --螺旋矩阵II
来源:互联网 发布:淘宝规蜜投诉 编辑:程序博客网 时间:2024/06/07 19:59
给你一个数n
生成一个包含1-n^2
的螺旋形矩阵
注意事项
n = 3
矩阵为
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]
]
/*本题就是按照螺旋的顺序把数字依次塞进去,我们可以维护上下左右边界的四个变量,一圈一圈往里面添加。最后要注意的是,如果n是奇数,要把中心那个点算上。*/public class Solution { public int[][] generateMatrix(int n) { int[][] res = new int[n][n]; int left = 0, right = n - 1, bottom = n - 1, top = 0; int num = 1;//num计数 while(left < right && top < bottom){ // 1.添加该圈第一行left for(int i = left; i < right; i++){ res[top][i] = num++; } // 2.添加最后一列top for(int i = top; i < bottom; i++){ res[i][right] = num++; } // 3.添加最后一行 for(int i = right; i > left; i--){ res[bottom][i] = num++; } // 4.添加第一列 for(int i = bottom; i > top; i--){ res[i][left] = num++; } //一圈之后减一圈 top++; bottom--; left++; right--; } // 如果是奇数,加上中间那个点 if(n % 2 == 1){ res[n / 2][n / 2] = num; } return res; }}
- lintcode-螺旋矩阵 II
- Lintcode 螺旋矩阵 II
- lintcode --螺旋矩阵II
- 螺旋矩阵 II -LintCode
- [LintCode]381.螺旋矩阵 II
- [LintCode] 螺旋矩阵II Spiral Matrix II
- lintcode,螺旋矩阵
- [LintCode]374.螺旋矩阵
- 螺旋矩阵-LintCode
- 螺旋矩阵II
- 螺旋矩阵 II
- [LintCode] 螺旋矩阵 Spiral Matrix
- *[Lintcode]Spiral Matrix螺旋矩阵
- LintCode 374-螺旋矩阵 状态机
- LintCode 螺旋矩阵 (新解法)
- LintCode-剑指Offer-(374)螺旋矩阵
- LintCode 374 螺旋矩阵的解决方法
- lintcode刷题——螺旋矩阵
- STM8 入门学习与实验(一)GPIO与UART
- gdb 如何调试内存地址
- Data Structure-2 Queue 循环队列,用数组实现
- strncpy字符串拷贝函数
- Android 仿QQ未读消息拖拽删除粘性控件效果
- lintcode --螺旋矩阵II
- wireshark 学习更进一步 之RST数据解读
- Hdu-5371 Hotaru's problem(马拉车算法)
- Java NIO系列教程(六) Selector
- bzoj 2301 problem b 莫比乌斯反演 解题报告
- qq获取用户信息
- js实现ajax
- 检查当前服务器系统版本
- java 实现的excel数据的导入导出