54. 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> res = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return res;
        int count = 0;
        int row = matrix.length;
        int col = matrix[0].length;
        while(count * 2 < row && count * 2 < col) {
            for (int i = count; i <= col - 1 - count; i++) { // 左上->右上
                res.add(matrix[count][i]);
            }
            for (int j = count + 1; j <= row - 1 - count; j++) { // 右上 -> 右下
                res.add(matrix[j][col - 1 - count]);
            }
            if (row - 2 * count == 1 || col - 2 * count == 1) break; // 只有1行或者1列情况就停止
            for (int i = col - 2 - count; i >= count; i--) { // 右下 -> 左下
                res.add(matrix[row - 1 - count][i]);
            }
            for (int j = row - 2 - count; j >= count + 1; j--) { // 左下 -> 左上
                res.add(matrix[j][count]);
            }
            count++;
        }
        return res;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s