Spiral Matrix

Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

这道题用的递归的思想,将最外面一层添加到result列表中,然后将剩下元素作为一个数组,做下一次递归,感觉有点土,晚点去搜点高大上的

 1 import java.util.ArrayList;
 2 import java.util.Arrays;
 3 import java.util.List;
 4 
 5 
 6 
 7 
 8 
 9 //class ListNode {
10 //      public int val;
11 //      public ListNode next;
12 //      ListNode(int x) {
13 //          val = x;
14 //          next = null;
15 //      }
16 //  }
17 
18 public class Solution {
19     List<Integer> result = new ArrayList<Integer>();
20     
21     public List<Integer> spiralOrder(int[][] matrix) {
22         if(null == matrix || matrix.length == 0)
23             return result;
24         
25         else if(matrix.length == 1 && matrix[0].length == 1)    //只有一个元素直接添加
26             result.add(matrix[0][0]);
27         else if(matrix[0].length == 1){                        //竖条
28             for(int i = 0; i < matrix.length; i++){
29                 result.add(matrix[i][0]);                //直接添加
30             }   
31         }
32         else if(matrix.length == 1){                    //横条
33             for(int i = 0; i < matrix[0].length; i++){
34                 result.add(matrix[0][i]);
35             }
36         }
37         else {
38             for(int i = 0; i < matrix[0].length; i++){    //添加第一排
39                 result.add(matrix[0][i]);
40             }
41             for(int i = 1; i < matrix.length; i++){        //添加最后一竖
42                 result.add(matrix[i][matrix[0].length - 1]);
43             }
44             for(int i = matrix[0].length - 2; i >= 0; i--){    //添加最后一排
45                 result.add(matrix[matrix.length - 1][i]);
46             }
47             for(int i = matrix.length - 2; i >= 1;i--){        //添加第一排
48                 result.add(matrix[i][0]);
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                 for(int i = 1; i < matrix.length - 1; i++){
53                     for(int j = 1; j < matrix[0].length - 1;j++){
54                         next[i - 1][j - 1] = matrix[i][j];
55                     }
56                 }
57                 spiralOrder(next);                                //递归求解下一个矩阵的值
58             }
59             
60         }
61         
62         return result;
63     }
64 }
原文地址:https://www.cnblogs.com/luckygxf/p/4151858.html