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

Spiral Matrix

时间:2015-07-24 10:29:26      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

问题描述

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> path = new ArrayList<Integer>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return path;
        }
        
        int i = 0, j = 0;
        int n = matrix.length, m = matrix[0].length;
        int cnt = n * m;
        int cyc = 0;
        
        while (true) {
            // to right
            while (j < m - cyc) {
                path.add(matrix[i][j++]);
            }
            --j;
            ++i;
            // to bottom
            while (i < n - cyc) {
                path.add(matrix[i++][j]);
            }
            --i;
            --j;
            if (path.size() == cnt) {
                break;
            }
            
            // to left
            while (j >= cyc) {
                path.add(matrix[i][j--]);
            }
            ++j;
            --i;
            // to top
            while (i > cyc) {
                path.add(matrix[i--][j]);
            }
            ++i;
            ++j;
            if (path.size() == cnt) {
                break;
            }
            
            ++cyc;
        }
        
        return path;
    }
}

  

Spiral Matrix

标签:

原文地址:http://www.cnblogs.com/harrygogo/p/4672549.html

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