59.螺旋矩阵

题目描述

给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

示例
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

在这里插入图片描述

思路

其实就是顺时针方向填入数组元素。
首先需要确定四个方向:右下左上。右:从1到3,下:从3到5,左:从5到7,上:从7到8,依次类推。
右方向的行数不变,列数每次加1;
下方向的列数不变,行数每次加1;
左方向的行数不变,列数每次减1;
上方向的列数不变,行数每次减1。
因此可以定义一个代表方向的二维数组direction[[0,1],[1,0],[0,-1],[-1,0]],每向数组中填入一个数后,就判断一次是否到达边界,如果到达边界,就转换一次方向。

代码
public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int num = 1;
        int row = 0;
        int column = 0;
        int maxNum = n * n;
        int directionIndex = 0;
        //代表右下左上四个方向
        int[][] direction = {{0,1},{1,0},{0,-1},{-1,0}};
        
        while (num <= maxNum) {
            matrix[row][column] = num;
            num++;
            //判断下一个位置是否到达边界
            int nextRow = row + direction[directionIndex][0];
            int nextColumn = column + direction[directionIndex][1];
            if (nextColumn >= n || nextRow >= n || matrix[nextRow][nextColumn] != 0 || nextRow < 0 || nextColumn < 0) {
                //到达边界,切换到下一个方向
                directionIndex = (directionIndex + 1) % 4;
            }
            row = row + direction[directionIndex][0];
            column = column + direction[directionIndex][1];
        }
        return matrix;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值