59. Spiral Matrix II
来源:互联网 发布:美国队长身材 知乎 编辑:程序博客网 时间:2024/06/03 17:21
题目
生成螺旋矩阵
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 class Solution { private int[,] matrix; private int elen; public int[,] GenerateMatrix(int n) { matrix = new int[n, n]; elen = 0; //element count spiral(0, n-1, n-1, 0); return matrix; } private void spiral(int top, int right, int bottom, int left) { if (top > bottom || left > right) return; //add first row for (int j = left; j <= right; j++) matrix[top, j] = ++elen; //add last column for (int i = top + 1; i <= bottom; i++) matrix[i, right] = ++elen; //add last row for (int j = right - 1; j >= left && top != bottom; j--) matrix[bottom, j] = ++elen; //add first column for (int i = bottom - 1; i > top && left != right; i--) matrix[i, left] = ++elen; spiral(top + 1, right - 1, bottom - 1, left + 1); }}
阅读全文
2 0
- 59.Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 190. Reverse Bits
- K
- 【3dsmax】下达Move命令之后,只能沿一条轴移动物体
- 使用ViewPager.PageTransformer自定义ViewPager
- C/C++学习笔记四(指针、数组)
- 59. Spiral Matrix II
- Saruman's Army POJ
- 【机器学习】线性回归
- Spring事务管理详解
- linux初学者-软件安装与管理篇
- tomcat 配置https协议
- Spring依赖注入方式
- 内部排序(2)——交换类排序
- sessionStorage 、localStorage 和 cookie比较