欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spiral Matrix

程序员文章站 2022-07-12 09:22:24
...

问题描述

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

下一篇: Spiral Matrix