[LeetCode]Spiral Matrix

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<Integer>();
        int row = matrix.length;
        if (row == 0) {
            return result;
        }
        int col = matrix[0].length;
        int level = (Math.min(row, col) + 1) / 2;
        for (int i = 0; i < level; i++) {
            for (int j = i; j < col - i; j++) {
                result.add(matrix[i][j]);
            }
            if (i == row - 1 - i) {
                break;
            }
            for (int j = i + 1; j < row - i; j++) {
                result.add(matrix[j][col - 1 - i]);
            }
            if (i == col - 1 - i) {
                break;
            }
            for (int j = col - 2 - i; j >= i; j--) {
                result.add(matrix[row - 1 - i][j]);
            }
            for (int j = row - 2 - i; j >= i + 1; j--) {
                result.add(matrix[j][i]);
            }
        }
        return result;
    }
}

 

posted @ 2015-12-02 08:17  Weizheng_Love_Coding  阅读(113)  评论(0编辑  收藏  举报