59. Spiral Matrix II (M)

本文介绍了一种算法,用于生成一个n×n的螺旋矩阵,矩阵元素从1到n²按螺旋顺序填充。提供了两种实现方式:通过方向变化和层遍历来完成矩阵填充,详细解析了代码实现过程。

Spiral Matrix II (M)

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

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

题意

将数1- n 2 n^2 n2按照螺旋顺时针的顺序填入一个 n x n 的矩阵中。

思路

方法与 54. Spiral Matrix 一样,在实现细节上甚至更加简单。


代码实现

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int[] iPlus = {0, 1, 0, -1};
        int[] jPlus = {1, 0, -1, 0};
        int direction = 0;				// 0123分别代表右下左上
        int i = 0, j = 0;
        
        for (int num = 1; num <= n * n; num++) {
            matrix[i][j] = num;
            // 先判断以当前方向走到的下一个位置是否合法,不合法则转向
            int nextI = i + iPlus[direction];
            int nextJ = j + jPlus[direction];
            if (nextI == -1 || nextI == n || nextJ == -1 || nextJ == n || matrix[nextI][nextJ] != 0) {
                direction = (direction + 1) % 4;
                i += iPlus[direction];
                j += jPlus[direction];
            } else {
                i = nextI;
                j = nextJ;
            }
        }
        
        return matrix;
    }
}

代码实现 - 层遍历

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        // 四个参数确定四条外边
        int rowUp = 0, rowDown = n - 1;
        int colLeft = 0, colRight = n - 1;
        int num = 1;

        while (rowUp <= rowDown && colLeft <= colRight) {
            for (int c = colLeft; c <= colRight; c++) {
                matrix[rowUp][c] = num++;
            }
            for (int r = rowUp + 1; r <= rowDown; r++) {
                matrix[r][colRight] = num++;
            }
            // 只有当前层不是一直线时,才有下边和左边
            if (rowUp < rowDown && colLeft < colRight) {
                for (int c = colRight - 1; c > colLeft; c--) {
                    matrix[rowDown][c] = num++;
                }
                for (int r = rowDown; r > rowUp; r--) {
                    matrix[r][colLeft] = num++;
                }
            }
            
            // 四边向内推进一层
            rowUp++;
            rowDown--;
            colLeft++;
            colRight--;
        }

        return matrix;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值