Spiral Matrix II 381

Question

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

Example

Given n = 3,

You should return the following matrix:

[ [ 1, 2, 3 ],

[ 8, 9, 4 ],

[ 7, 6, 5 ] ]

Solution

与Spiral Matrix一样,只不过这次是往里加数。

代码如下:

public class Solution {
    /**
     * @param n an integer
     * @return a square matrix
     */
    public int[][] generateMatrix(int n) {
        // Write your code here
        int[][] matrix = new int[n][n];

        int number = 1;
        int count = 0;
        while(count * 2 < n){
            for(int i = count; i < n - count; i++){
                matrix[count][i] = number++;
            }

            for(int i = count + 1; i < n - count; i++){
                matrix[i][n - 1 - count] = number++;
            }

            if(n - count * 2 == 1){
                break;
            }

            for(int i = n - 2 - count; i >= count; i--){
                matrix[n - 1 - count][i] = number++;
            }

            for(int i = n - 2 - count; i > count; i--){
                matrix[i][count] = number++;
            }
            count++;
        }
        return matrix;
    }
}

results matching ""

    No results matching ""