【Leetcode】Spiral Matrix II
来源:互联网 发布:sql server 2008下载 编辑:程序博客网 时间:2024/06/06 11:47
题目链接:https://leetcode.com/problems/spiral-matrix-ii/
题目:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
思路:
1、由外向内一圈一圈的计算,首先计算有几圈,用dim表示,根据dim控制循环次,复杂的地方在于判断每圈每段的起始位置。这种方法思路简单,实现麻烦。
2、用递归实现,参考 http://fisherlei.blogspot.com/2013/04/leetcode-spiral-matrix-ii-solution.html 看起来也挺费劲的。
算法1:
public int[][] generateMatrix(int n) {int matrix[][] = new int[n][n];int dim = n / 2;if (n % 2 != 0)dim++;int s = 1;for (int i = 0; i < dim; i++) {for (int j = i; j < n - i; j++) {//上matrix[i][j] = s;s++;}for (int x = i + 1; x < n - i; x++) {//右matrix[x][n - i - 1] = s;s++;}for (int x = n - 2 - i; x >= i; x--) {//下matrix[n - 1 - i][x] = s;s++;}for (int x = n - 2 - i; x > i; x--) {//左matrix[x][i] = s;s++;}}return matrix;}
0 0
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix II
- LeetCode : Spiral Matrix II
- [LeetCode] Spiral Matrix II
- [LeetCode]Spiral Matrix II
- [leetcode]Spiral Matrix II
- LeetCode-Spiral Matrix II
- [leetcode] Spiral Matrix II
- LeetCode - Spiral Matrix II
- Leetcode: Spiral Matrix II
- 【LeetCode】Spiral Matrix II
- Leetcode Spiral Matrix II
- [LeetCode] Spiral Matrix II
- LeetCode | Spiral Matrix II
- LeetCode Spiral Matrix II
- Leetcode: Spiral Matrix II
- Spiral Matrix II -- LeetCode
- sax/dom/jdom/dom4j的区别?
- 黑马程序员——C语言基础---指针
- hdoj 5592 ZYB's Premutation 【线段树插空】
- 从DeepLearnToolbox-master看CNN
- Android生成keystore的两种方式
- 【Leetcode】Spiral Matrix II
- 同时安装Java 1.7和1.8
- 【tmp】LR(0)
- 02_Java 重写(Override)与重载(Overload)
- 深入了解scanf() getchar()和gets()等函数之间的区别
- mysql配置优化(windows下my.ini) 参数设置
- MySQL 使用-一
- Java缓存机制案例
- Shiro介绍(一):网络上几张图的解读