码迷,mamicode.com
首页 > 其他好文 > 详细

Jan 18 - Spiral Matrix; 2D Array;

时间:2016-01-19 12:05:44      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

代码:

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> resultList = new ArrayList<>();
        int row = matrix.length;
        if(row == 0) return resultList;
        int col = matrix[0].length;
        if(col == 0) return resultList;
        int n = row < col? row : col;

        for(int i = 0; i <= n/2; i++){
            int width = col - 1 - 2*i;
            int height = row - 1 - 2*i;
            if(width < 0 || height < 0) break;
            if(height == 0 && width == 0){
                resultList.add(matrix[i][i]);
                break;
            }
            if(height == 0) {
                for(int j = 0; j <= width; j++) resultList.add(matrix[i][i+j]);
                break;
            }
            if(width == 0){
                for(int j = 0; j <= height; j++) resultList.add(matrix[i+j][i]);
                break;
            }
            for(int j = 0; j < (width+height)*2; j++){
                if(j < width) resultList.add(matrix[i][i+j]);
                else if(j < width+height && j >= width) resultList.add(matrix[i+j-width][i+width]);
                else if(j < 2*width+height && j >= width+height) resultList.add(matrix[i+height][i+width-(j-width-height)]);
                else resultList.add(matrix[i+height-(j-2*width-height)][i]);
                /*
                int top_left = matrix[i][i];
                int top_right = matrix[i][i+num];
                int bottom_right = matrix[i+num][i+num];
                int bottom_left = matrix[i+num][i];
                */
            }
        }
        return resultList;
    }
}

  

Jan 18 - Spiral Matrix; 2D Array;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5141378.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!