题目: 螺旋矩阵

来自智得网
跳转至: 导航、​ 搜索

分析

位置法

螺旋矩阵在螺旋遍历的过程中,走一圈需要经历四次变向,从左到右,从上到下,从右到左,从下到上。通过计算每次变向时机即可完成旋转。

题解

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans = new ArrayList<>();
        if (matrix.length == 0)
            return ans;
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;
        while (true) {
            for (int i = left; i <= right; i++)
                ans.add(matrix[top][i]);
            top++;
            if (left > right || top > bottom)
                break;

            for (int i = top; i <= bottom; i++)
                ans.add(matrix[i][right]);
            right--;
            if (left > right || top > bottom)
                break;

            for (int i = right; i >= left; i--)
                ans.add(matrix[bottom][i]);
            bottom--;
            if (left > right || top > bottom)
                break;

            for (int i = bottom; i >= top; i--)
                ans.add(matrix[i][left]);
            left++;
            if (left > right || top > bottom)
                break;
        }
        return ans;
    }
}