Spiral Matrix II
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 import java.util.ArrayList; 2 import java.util.Arrays; 3 import java.util.List; 4 5 6 7 public class Solution { 8 // List<Integer> result = new ArrayList<Integer>(); 9 int result[][]; 10 int count = 1; 11 public int[][] generateMatrix(int n) { 12 13 result = new int[n][n]; 14 if(0 == n) 15 return result; 16 spiralOrder(result); 17 return result; 18 } 19 20 public void spiralOrder(int[][] matrix) { 21 22 23 if(matrix.length == 1 && matrix[0].length == 1) //只有一个元素直接添加 24 { 25 matrix[0][0] = count++; 26 } 27 else if(matrix[0].length == 1){ //竖条 28 for(int i = 0; i < matrix.length; i++){ 29 matrix[i][0] = count++; 30 } 31 } 32 else if(matrix.length == 1){ //横条 33 for(int i = 0; i < matrix[0].length; i++){ 34 matrix[0][i] = count++; 35 } 36 } 37 else { 38 for(int i = 0; i < matrix[0].length; i++){ //添加第一排 39 matrix[0][i] = count++; 40 } 41 for(int i = 1; i < matrix.length; i++){ //添加最后一竖 42 matrix[i][matrix[0].length - 1] = count++; 43 } 44 for(int i = matrix[0].length - 2; i >= 0; i--){ //添加最后一排 45 matrix[matrix.length - 1][i] = count++; 46 } 47 for(int i = matrix.length - 2; i >= 1;i--){ //添加第一排 48 matrix[i][0] = count++; 49 } 50 if(matrix.length - 2 != 0 && matrix[0].length - 2 != 0){ 51 int next[][] = new int[matrix.length - 2][matrix[0].length - 2]; 52 spiralOrder(next); //递归求解下一个矩阵的值 53 for(int i = 1; i < matrix.length - 1; i++){ 54 for(int j = 1; j < matrix[0].length - 1;j++){ 55 matrix[i][j] = next[i - 1][j - 1]; 56 } 57 } 58 59 } 60 61 } 62 } 63 }
Please call me JiangYouDang!