[leetcode] 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].

https://oj.leetcode.com/problems/spiral-matrix/

思路:这题目不难理解,就是注意边界情况, 推荐用 上下左右4个bar的方法,简单不易出错。

import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (matrix == null || matrix.length < 1 || matrix[0].length < 1)
            return res;
        int left = 0;
        int right = matrix[0].length - 1;
        int top = 0;
        int bottom = matrix.length - 1;

        while (left <= right && top <= bottom) {
            int i;
            for (i = left; i <= right; i++)
                res.add(matrix[top][i]);

            for (i = top + 1; i <= bottom; i++)
                res.add(matrix[i][right]);

            if (top < bottom)//corner case, no need back to left if top==bottom
                for (i = right - 1; i >= left; i--)
                    res.add(matrix[bottom][i]);

            if (left < right)//corner case, no need back up if left==right
                for (i = bottom - 1; i >= top + 1; i--)
                    res.add(matrix[i][left]);

            top++;
            bottom--;
            left++;
            right--;
        }

        return res;

    }

    public static void main(String[] args) {
        int[][] matrix = new int[][] { { 1,2 }, { 5,6 }, { 9,10 } };
        System.out.println(new Solution().spiralOrder(matrix));
    }
}







你可能感兴趣的:(java,LeetCode,Matrix)