LeetCode 59. Spiral Matrix II(螺旋矩阵)
2016-05-21 07:50
387 查看
原题网址: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 =
You should return the following matrix:
方法:递归。
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 ] ]
方法:递归。
public class Solution { private void spiral(int[][] matrix, int value, int left, int top, int right, int bottom) { if (left>right || top>bottom) return; if (left==right && top==bottom) { matrix[top][left]=value; return; } for(int j=left; j<right; j++) matrix[top][j]=value++; for(int i=top; i<bottom; i++) matrix[i][right]=value++; for(int j=right; j>left; j--) matrix[bottom][j]=value++; for(int i=bottom; i>top; i--) matrix[i][left]=value++; spiral(matrix, value, left+1, top+1, right-1, bottom-1); } public int[][] generateMatrix(int n) { int[][] matrix = new int ; spiral(matrix, 1, 0, 0, n-1, n-1); return matrix; } }
相关文章推荐
- 设计模式学习笔记之命令模式
- 蓝牙OBEX剖析(一)
- 有很多东西还是有用的
- 修改weblogic jvm启动参数
- 函数接口
- LeetCode 58. Length of Last Word(最后一个单词的长度)
- 线程间协作的二种方式:wait,notify,notifyAll和condition
- LeetCode 57. Insert Interval(插入区间)
- js时间戳格式化成日期格式
- Playing with ptrace, Part I
- [Java]阶段性知识点、技术总结
- HDFS的搭建
- Lambda表达式操作引用值,而非对象
- centosx64位寄存器
- Lambda表达式类型推断
- C#迭代器
- Android Exception总结
- java环境配置为1.7jdk为什么cmd java -version查看版本是1.8
- .net5的异步
- OSChina 周六乱弹 ——自从我知道了地震的含义以后……