LeetCode 题解(170): Spiral Matrix II

题目:

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

题解:

纯二维数组操作。

C++版:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> result(n, vector<int>(n, 0));
        int num = 1;
        int c = ceil((double)n / 2);
        for(int i = 0; i < c; i++) {
            for(int j = i; j < n - i; j++)
                result[i][j] = num++;
            for(int j = i + 1; j < n - i; j++)
                result[j][n - i - 1] = num++;
            for(int j = n - i - 2; j >= i; j--)
                result[n - i - 1][j] = num++;
            for(int j = n - i - 2; j >= i + 1; j--)
                result[j][i] = num++;
        }
        return result;
    }
};

Java版:

public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int c = (int)Math.ceil((double)n / 2);
        int num = 1;
        for(int i = 0; i < c; i++) {
            for(int j = i; j < n - i; j++)
                result[i][j] = num++;
            for(int j = i + 1; j < n - i; j++)
                result[j][n - i - 1] = num++;
            for(int j = n - i - 2; j >= i; j--)
                result[n - i - 1][j] = num++;
            for(int j = n - i - 2; j >= i + 1; j--)
                result[j][i] = num++;
        }
        return result;
    }
}

Python版:

import math

class Solution:
    # @param {integer} n
    # @return {integer[][]}
    def generateMatrix(self, n):
        result = [[0 for i in range(n)] for j in range(n)]
        num = 1
        c = int(math.ceil(float(n) / 2))
        for i in range(c):
            for j in range(i, n - i):
                result[i][j] = num
                num += 1
            for j in range(i + 1, n - i):
                result[j][n - i - 1] = num
                num += 1
            for j in range(n - i - 2, i - 1, -1):
                result[n - i - 1][j] = num
                num += 1
            for j in range(n - i - 2, i, -1):
                result[j][i] = num
                num += 1
        return result

你可能感兴趣的:(Algorithm,LeetCode,面试题)