Spiral Matrix II

https://leetcode.com/problems/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 ]

]

解题思路:

和 Spiral Matrix 基本类似,只需要加入一个递增的值,循环打印就可以了。

public class Solution {

    public int[][] generateMatrix(int n) {

        int[][] matrix = new int[n][n];

        if(n == 0){

            return matrix;

        }

        

        int left = 0, right = matrix[0].length - 1, top = 0, bottom = matrix.length - 1;

        int max = 0;

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

            max = spiralEdge(matrix, left, right, top, bottom, max);

            left++;

            right--;

            top++;

            bottom--;

        }

        return matrix;

    }

    

    public int spiralEdge(int[][] matrix, int left, int right, int top, int bottom, int max){

        //打印上边

        for(int i = left; i <= right; i++){

            matrix[top][i] = ++max;

        }

        //打印右边

        for(int i = top + 1; i <= bottom; i++){

            matrix[i][right] = ++max;

        }

        if(left == right || top == bottom){

            return max;

        }

        //打印下边

        for(int i = right - 1; i >= left; i--){

            matrix[bottom][i] = ++max;

        }

        //打印左边

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

            matrix[i][left] = ++max;

        }

        return max;

    }

}

 

你可能感兴趣的:(Matrix)