码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode: Spiral Matrix. Java

时间:2014-10-27 12:51:24      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   二维数组   arraylist   

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 class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<Integer>();
        int m = matrix.length;
        if(m == 0) return res;
        int n = matrix[0].length;
        //循环次数小于m/2和n/2
        for(int i = 0; i < m/2 && i < n/2; i++){
            for(int j = 0; j < n - 1 - i * 2; j++)
                res.add(matrix[i][i+j]);
            for(int j = 0; j < m - 1 - i * 2; j++)
                res.add(matrix[i+j][n-i-1]);
            for(int j = 0; j < n - 1 - i * 2; j++)
                res.add(matrix[m-i-1][n-i-1-j]);
            for(int j = 0; j < m - 1 - i * 2; j++)
                res.add(matrix[m-i-1-j][i]);
        }
        //循环结束后如果行数/列数是奇数,则还剩一行/列
        if(m % 2 != 0 && m <= n){
            for(int j = 0; j < n - (m/2) * 2; j++)
                res.add(matrix[m/2][m/2+j]);  
        }
        else if(n % 2 != 0 && m > n){
            for(int j = 0; j < m - (n/2) * 2; j++)
                 res.add(matrix[n/2+j][n/2]);
        }
        return res;
    }
}


Leetcode: Spiral Matrix. Java

标签:java   leetcode   二维数组   arraylist   

原文地址:http://blog.csdn.net/muscler/article/details/40504915

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