码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】Spiral Matrix

时间:2016-05-30 15:31:54      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/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].

思路:

注意细节。  

首先计算需要遍历几“圈”,将每圈分成四次不同方向的遍历。    

算法

public List<Integer> spiralOrder(int[][] matrix) {  
    List<Integer> list = new ArrayList<Integer>();  
    if (matrix.length == 0) {  
        return list;  
    }  
    // n行m列  
    int n = matrix.length;  
    int m = matrix[0].length;  
    // dim是矩阵的圈数  
    int dim = Math.min(n, m) / 2;  
    if (Math.min(n, m) == 1) {  
        for (int i = 0; i < n; i++) {  
            for (int j = 0; j < m; j++) {  
                list.add(matrix[i][j]);  
            }  
        }  
        return list;  
    }  
    if (Math.min(n, m) % 2 != 0)  
        dim++;  
  
    for (int i = 0; i < dim; i++) {  
        for (int j = i; j < m - i; j++) {  
            list.add(matrix[i][j]);  
        }  
        if (i + 1 == (n - i))  
            break;  
        for (int x = i + 1; x < n - i; x++) {  
            list.add(matrix[x][m - i - 1]);  
        }  
        if (m - 2 - i < i)  
            break;  
        for (int x = m - 2 - i; x >= i && x < m && x >= 0; x--) {  
            list.add(matrix[n - 1 - i][x]);  
        }  
  
        for (int x = n - 2 - i; x > i; x--) {  
            list.add(matrix[x][i]);  
        }  
    }  
    return list;  
}  


【Leetcode】Spiral Matrix

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51520482

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!