[leetcode]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 [][]resMatrix = new int[n][n];
        if(n == 0) return resMatrix;
        int widtn = n, len = n;
        int [][]flagArray = new int[widtn][len];
        int direction = 0;  // 初始方向
        int currentX = 0, currentY = 0;
        int []directionY = {1, 0, -1, 0};
        int []directionX = {0, 1, 0, -1};
        int count = len * widtn;
        while(count > 0){
            resMatrix[currentX][currentY] = n * n - count + 1;
            flagArray[currentX][currentY] = 1;
            if(currentX + directionX[direction] < widtn &&
                    currentX + directionX[direction] >= 0 &&
                    currentY + directionY[direction] < len &&
                    currentY + directionY[direction] >= 0 &&
                    flagArray[currentX + directionX[direction]][currentY + directionY[direction]] != 1){
                currentX = currentX + directionX[direction];
                currentY = currentY + directionY[direction];
            }else{
                direction = (++ direction) % 4;
                currentX = currentX + directionX[direction];
                currentY = currentY + directionY[direction];
            }
            count --;
        }
        return resMatrix;
    }
}

题目链接:https://leetcode.com/problems/spiral-matrix-ii/

你可能感兴趣的:(LeetCode)