leetcode54. 螺旋矩阵

12 阅读1分钟
class Solution {

    public List<Integer> spiralOrder(int[][] matrix) {

        List<Integer> result = new ArrayList<>();

        int m = matrix.length;//3
        int n = matrix[0].length;//3


        // 四个边界
        int top = 0;
        int bottom = m - 1;//2

        int left = 0;
        int right = n - 1;//2


        while(top <= bottom && left <= right){


            // 1. 从左到右遍历顶部
            for(int j = left; j <= right; j++){

                result.add(matrix[top][j]);

            }

            top++;


            // 2. 从上到下遍历右边
            for(int i = top; i <= bottom; i++){

                result.add(matrix[i][right]);

            }

            right--;


            // 3. 从右到左遍历底部
            if(top <= bottom){

                for(int j = right; j >= left; j--){

                    result.add(matrix[bottom][j]);

                }

                bottom--;

            }


            // 4. 从下到上遍历左边
            if(left <= right){

                for(int i = bottom; i >= top; i--){

                    result.add(matrix[i][left]);

                }

                left++;

            }

        }


        return result;
    }
}

流程图