54#螺旋矩阵

孤街浪徒 提交于 2020-01-25 18:05:31

题目:

题解:

public List<Integer> spiralOrder(int[][] matrix) {
        if (matrix.length == 0) return new ArrayList();
        int m = matrix.length;
        int n = matrix[0].length;
        ArrayList result = new ArrayList();
        int north = 0;  //北
        int south = m-1;  //南
        int west = 0;   //西
        int east = n-1;   //东
        int count1 = 0;
        int count2 = 1;
        result.add(matrix[0][0]);
        while (result.size()<m*n){
            if (north<(m+1)/2){
                while (west != east){
                    result.add(matrix[count1][++west]);
                    if (result.size()==m*n) return result;
                }
                east--;
            }
            if (west>=(n-1)/2){
                while (north != south){
                    result.add(matrix[++north][west]);
                    if (result.size()==m*n) return result;
                }
            }
            while (west != count1){
                result.add(matrix[north][--west]);
                if (result.size()==m*n) return result;
            }
            south--;
            count1++;
            while (north != count2){
                result.add(matrix[--north][west]);
                if (result.size()==m*n) return result;
            }
            count2++;
        }
        return result;
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!