LeetCode 59 螺旋矩阵II

LeetCode 59 螺旋矩阵II

该题与leetcode 54 螺旋矩阵I异曲同工,同样需要使用方向数组来进行周期性的方向调整

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:37.3 MB, 在所有 Java 提交中击败了80.52%的用户

class Solution {
    public int[][] generateMatrix(int n) {
        //利用方向数组: 右、下、左、上
        int[][] directs = new int[][]{
            {0,1},{1,0},{0,-1},{-1,0}
        };
        
        //输出矩阵
        int[][] matrix = new int[n][n];
        //初始打印值、方向、坐标
        int num = 1, direct = 0, row = 0 , col = 0;
        while(num <= (long)Math.pow(n,2)) {
            //输出当前值
            matrix[row][col] = num;
            num++;
            //当前方向下一点非法,则调整方向: 数组边界越界、碰到已遍历位置
            if(((row+directs[direct][0])<0 ||
                (row+directs[direct][0])>=n) ||
                ((col+directs[direct][1])<0 ||
                (col+directs[direct][1])>=n) ||
                matrix[row+directs[direct][0]][col+directs[direct][1]]!=0) 
                direct++;
            //调整方向,以4为周期循环
            direct = direct%4;
            //下一点坐标计算
            row += directs[direct][0];
            col += directs[direct][1];
        }

        return matrix;
    }
}
posted @ 2020-07-31 09:19  CodeSPA  阅读(76)  评论(0编辑  收藏  举报