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 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;
    }
}

  

posted @ 2015-07-24 09:59  Chapter  阅读(103)  评论(0编辑  收藏  举报