Spiral Matrix, Leetcode 解题笔记

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 ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> ret = new ArrayList<Integer>();
        int row = 0;
        int col = 0;
        int row_end = matrix.length;
        if(row_end == 0) return ret;
        int col_end = matrix[0].length;
        if(col_end == 0) return ret;
        row_end--;
        col_end--;
        int num = (row_end+1) * (col_end+1);
        
        while(true){
            for(int i = col; i <= col_end; i++){
                ret.add(matrix[row][i]);
            }
            row++;
            if(ret.size() == num) break;
            for(int j = row; j <= row_end; j++){
                ret.add(matrix[j][col_end]);
            }
            col_end--;
            if(ret.size() == num) break;
            for(int i = col_end; i >= col; i--){
                ret.add(matrix[row_end][i]);
            }
            row_end--;
            if(ret.size() == num) break;
            for(int j = row_end; j >= row; j--){
                ret.add(matrix[j][col]);
            }
            col++;
            if(ret.size() == num) break;
        }
        return ret;
        
    }
}
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