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