leetcode59

54. Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

59. Spiral Matrix II
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

模拟题。
1.都是用top, right, bottom, left四条线遍历。在top<bottom && left < right的时候持续。
2.top遍历点为[left, right), right遍历点为[top, bottom),bottom遍历点为[right, left),left遍历点为[bottom, top)。这样最外面一圈是正好扒光的。
3.遍历完top++bottom--left++right--
4.如果是n*n,且n为奇数,中间会剩下一个点要补,坐标就是[top][left]了。
5.如果是m*n,那中间可能剩下一条横的或竖的要补,横的坐标就是[top][[left~right]]了,竖的就是[[top~bottom]][left]了。如果是一个点的话注意只处理其中一次。

1.实现leetcode54 - Spiral Matrix

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return list;
        }

        int row = matrix.length, col = matrix[0].length;
        int top = 0, bottom = row - 1, left = 0, right = col - 1;
        
        while (top < bottom && left < right) {
            for (int i = left; i < right; i++) list.add(matrix[top][i]);
            for (int i = top; i < bottom; i++) list.add(matrix[i][right]);
            for (int i = right; i > left; i--) list.add(matrix[bottom][i]);
            for (int i = bottom; i > top; i--) list.add(matrix[i][left]);
            top++;
            bottom--;
            left++;
            right--;
        }
        
        if (top == bottom) {
            for (int i = left; i <= right; i++) {
                list.add(matrix[top][i]);
            }
        } else if (left == right) {
            for (int i = top; i <= bottom; i++) {
                list.add(matrix[i][left]);
            }
        }
        return list;
    }
}

2.实现leetcode59 - Spiral Matrix II

class Solution {
    public int[][] generateMatrix(int n) {
        if (n <= 0) return new int[0][0];
        int[][] ans = new int[n][n];
        int top = 0, bottom = n - 1, left = 0, right = n - 1;
        
        int num = 1;
        while (top < bottom && left < right) {
            for (int i = left; i < right; i++) ans[top][i] = num++;
            for (int i = top; i < bottom; i++) ans[i][right] = num++;
            for (int i = right; i > left; i--) ans[bottom][i] = num++;
            for (int i = bottom; i > top; i--) ans[i][left] = num++;
            top++;
            bottom--;
            left++;
            right--;
        }
        
        if (n % 2 == 1) {
            ans[n / 2][n / 2] = num;
        }
        return ans;
    }
}
原文地址:https://www.cnblogs.com/jasminemzy/p/9666867.html