zoukankan      html  css  js  c++  java
  • Spiral Matrix leetcode java

    题目

    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].

    题解
    这道题是实现题。

    考虑2个初始条件,如果矩阵只有一行或者一列,那么无需转圈,依次输出即可。

    其他情况均需转圈:从左到右,从上到下,从右到左,从下到上。 从大圈依次循环到小圈即可。

    代码如下:

     1    public ArrayList<Integer> spiralOrder(int[][] matrix) {
     2         ArrayList<Integer> result = new ArrayList<Integer>();
     3         if(matrix == null || matrix.length == 0)
     4             return result;
     5  
     6         int m = matrix.length;
     7         int n = matrix[0].length;
     8  
     9         int x=0; 
    10         int y=0;
    11  
    12         while(m>0 && n>0){
    13  
    14             //if one row/column left, no circle can be formed
    15             if(m==1){
    16                 for(int i=0; i<n; i++){
    17                     result.add(matrix[x][y++]);
    18                 }
    19                 break;
    20             }else if(n==1){
    21                 for(int i=0; i<m; i++){
    22                     result.add(matrix[x++][y]);
    23                 }
    24                 break;
    25             }
    26  
    27             //below, process a circle
    28  
    29             //top - move right
    30             for(int i=0;i<n-1;i++)
    31                 result.add(matrix[x][y++]);
    32  
    33             //right - move down
    34             for(int i=0;i<m-1;i++)
    35                 result.add(matrix[x++][y]);
    36  
    37             //bottom - move left
    38             for(int i=0;i<n-1;i++)
    39                 result.add(matrix[x][y--]);
    40  
    41             //left - move up
    42             for(int i=0;i<m-1;i++)
    43                 result.add(matrix[x--][y]);
    44  
    45             x++;
    46             y++;
    47             m=m-2;
    48             n=n-2;
    49         }
    50  
    51         return result;
    52     }

    Reference:http://www.programcreek.com/2013/01/leetcode-spiral-matrix-java/

  • 相关阅读:
    strspn实现 查找第一个不在指定字符串中出现的字符
    strstr 的实现 即 字符串中查找子字符串第一次出现的位置
    strcspn
    将字符串中的大写字母变成小写字母
    strrchr 字符在字符串中最后一次出现的位置
    strchr 字符c在字符串中出现的位置 实现
    qsort库函数 排序
    strncmp实现
    strcmp实现
    ACM/ICPC题目输入情形及其处理方法
  • 原文地址:https://www.cnblogs.com/springfor/p/3887890.html
Copyright © 2011-2022 走看看