zoukankan      html  css  js  c++  java
  • Spiral Matrix

     1 public class Solution {
     2     public ArrayList<Integer> spiralOrder(int[][] matrix) {
     3         // IMPORTANT: Please reset any member data you declared, as
     4         // the same Solution instance will be reused for each test case.
     5         ArrayList<Integer> result = new ArrayList<Integer>();
     6         if(matrix == null||matrix.length == 0)
     7             return result;
     8         int m = matrix.length;
     9         int n = matrix[0].length;
    10         spiralRecur(matrix, 0, result, m, n);
    11         return result;
    12     }
    13     
    14     private void spiralRecur(int[][] matrix, int layer, ArrayList<Integer> result, int m, int n){
    15         int mlen = m - 2 * layer;
    16         int nlen = n - 2 * layer;
    17         
    18         if(mlen <= 0 || nlen <= 0)
    19             return;
    20         if(mlen == 1 && nlen == 1)
    21             result.add(matrix[layer][layer]);
    22         else if(mlen == 1){
    23             for(int i = 0; i < nlen; i++)
    24             result.add(matrix[layer][layer + i]);
    25         }
    26         else if(nlen == 1){
    27             for(int i = 0; i < mlen; i++)
    28             result.add(matrix[layer + i][layer]);
    29         }
    30         else{
    31             
    32             for(int i = 0; i < nlen - 1; i++)
    33                 result.add(matrix[layer][layer + i]);
    34                 
    35             for(int i = 0; i < mlen - 1; i++)
    36                 result.add(matrix[layer + i][layer + nlen - 1]);
    37                 
    38             for(int i = 0; i < nlen - 1; i++)
    39                 result.add(matrix[layer + mlen - 1][layer + nlen - 1 - i]);
    40                 
    41             for(int i = 0; i < mlen - 1; i++)
    42                 result.add(matrix[layer + mlen - 1 - i][layer]);
    43         }
    44         spiralRecur(matrix, layer + 1, result, m ,n);
    45     }
    46 }
  • 相关阅读:
    On the fly test
    Spec Explorer 工具学习
    C# Static修饰符的作用
    [转]C#静态方法与非静态方法的比较
    如何获取网站服务器运行状态
    C#快速整理代码格式
    UI auto程序结构组织方式
    TestClass必须是public的
    VS2012如何显示行号
    Error: member names cannot be the same as their enclosing type
  • 原文地址:https://www.cnblogs.com/jasonC/p/3432991.html
Copyright © 2011-2022 走看看