1. 程式人生 > 其它 >模擬過程-螺旋矩陣2

模擬過程-螺旋矩陣2

模擬過程-螺旋矩陣2

螺旋矩陣2
模擬遍歷過程, 要按照外圈到內圈進行迴圈, 考慮奇數偶數不同。

題解

public class Solution {
    public int[][] generateMatrix(int n) {
        // 定義迴圈的偏移起點,迴圈次數
        int startX = 0, startY = 0;
        int loop = n / 2;

        // 定義初始賦值
        int count = 1;

        // 初始化陣列
        int[][] result = new int[n][n];

        // 偏移量,每個圈的寬度減2
        int offset = 0;

        while (loop > 0) {
            int size = n - offset;
            //模擬上側從左到右:左閉右開
            for (int j = startY; j < startY + size - 1; j++) {
                result[startX][j] = count++;
            }
            //模擬右側從上到下
            for (int i = startX; i < startX + size - 1; i++) {
                result[i][startY + (size - 1)] = count++;
            }
            //模擬下側從右到左
            for (int j = startY + size - 1; j > startY; j--) {
                result[startX + (size - 1)][j] = count++;
            }
            //模擬左側從下到上
            for (int i = startX + size - 1; i > startX; i--) {
                result[i][startY] = count++;
            }
            //更新引數
            loop--;
            startX += 1;
            startY += 1;
            offset += 2;
        }
        // 如果是奇數, 中間還有一個賦值
        if (n % 2 == 1) {
            result[n / 2][n / 2] = count;
        }
        return result;
    }
}