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,

You should return the following matrix:

[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
] 这道题接着上面那道题,是一个逆过程,只要稍微改一下就好了,因为上面一题螺旋式的遍历了整个数组,只要在遍历过程中将数字填进去就好了
 import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; public class Solution {
// List<Integer> result = new ArrayList<Integer>();
int result[][];
int count = 1;
public int[][] generateMatrix(int n) { result = new int[n][n];
if(0 == n)
return result;
spiralOrder(result);
return result;
} public void spiralOrder(int[][] matrix) { if(matrix.length == 1 && matrix[0].length == 1) //只有一个元素直接添加
{
matrix[0][0] = count++;
}
else if(matrix[0].length == 1){ //竖条
for(int i = 0; i < matrix.length; i++){
matrix[i][0] = count++;
}
}
else if(matrix.length == 1){ //横条
for(int i = 0; i < matrix[0].length; i++){
matrix[0][i] = count++;
}
}
else {
for(int i = 0; i < matrix[0].length; i++){ //添加第一排
matrix[0][i] = count++;
}
for(int i = 1; i < matrix.length; i++){ //添加最后一竖
matrix[i][matrix[0].length - 1] = count++;
}
for(int i = matrix[0].length - 2; i >= 0; i--){ //添加最后一排
matrix[matrix.length - 1][i] = count++;
}
for(int i = matrix.length - 2; i >= 1;i--){ //添加第一排
matrix[i][0] = count++;
}
if(matrix.length - 2 != 0 && matrix[0].length - 2 != 0){
int next[][] = new int[matrix.length - 2][matrix[0].length - 2];
spiralOrder(next); //递归求解下一个矩阵的值
for(int i = 1; i < matrix.length - 1; i++){
for(int j = 1; j < matrix[0].length - 1;j++){
matrix[i][j] = next[i - 1][j - 1];
}
} } }
}
}

最新文章

  1. CSS清浮动
  2. POJ 1260 Pearls 简单dp
  3. React Native填坑之旅--Button篇
  4. Verilog
  5. poj 1679 http://poj.org/problem?id=1679
  6. SQL中空值与NULL区别
  7. wuzhicms页面报错 Notice 错误,如何关闭错误显示!
  8. ssh中使用set的地方及ref
  9. allocator例子
  10. c++ 09
  11. JavaScript编程:javaScript核心基础语法
  12. 采用 matlab 阅读SAR 元数据
  13. 详解 try-with-resource
  14. Codeforces Round #554 (Div. 2) C. Neko does Maths (简单推导)
  15. linux vbundle插件配置
  16. nodejs eggjs框架 爬虫 readhub.me
  17. SpringMvc的基本流程
  18. Fernflower 反编译.class文件
  19. 关于vue2.0获取后端数据
  20. Incorrect Invoice Ref.

热门文章

  1. 【.NET基础】--委托、事件、线程(3)
  2. 清除层div浮动
  3. 【转】C#之继承
  4. 关于GrideView Item点击后出现错乱重叠的情况
  5. 各个手机APP客户端内置浏览器useragent
  6. 简单的MySQL数据库主从同步配置
  7. IE6中position:fixed无效问题解决
  8. 在hibernate中使用c3p0数据源
  9. 去掉影响效率的where 1=1
  10. C89 和 C99的标准比较