package com.zmz.algorithm.array;

/**
 * @author 张明泽
 * Create by 2022/5/23 16:20
 * 螺旋矩阵二
 * LeetCode-59
 */
public class SpiralMatrix2 {
    public static void main(String[] args) {
        int[][] result = matrix2(4);
        for (int i = 0; i < result.length; i++) {
            for (int j = 0; j < result.length; j++) {
                System.out.print(result[i][j]);
            }
            System.out.println();
        }
    }
    public static int[][] matrix(int n) {
        int[][] arr = new int[n][n];
        int number = 1;
        int total = n * n;
        int left = 0;
        int top = 0;
        int right = n - 1;
        int bottom = n - 1;
        while (number <= total) {
            for (int i = left; i <= right; i++) {
                arr[top][i] = number++;
            }
            top++;
            for (int i = top; i <= bottom; i++) {
                arr[i][right] = number++;
            }
            right--;
            for (int i = right; i >= left; i--) {
                arr[bottom][i] = number++;
            }
            bottom--;
            for (int i = bottom; i >= top; i--) {
                arr[i][left] = number++;
            }
            left++;
        }
        return arr;
    }
    public static int[][] matrix2(int n) {
        int[][] arr = new int[n][n];
        int number = 1;
        int left = 0;
        int top = 0;
        int right = n - 1;
        int bottom = n - 1;
        while (left <= right && top <= bottom) {
            for (int i = left; i <= right; i++) {
                arr[top][i] = number++;
            }
            top++;
            for (int i = top; i <= bottom; i++) {
                arr[i][right] = number++;
            }
            right--;
            for (int i = right; i >= left; i--) {
                arr[bottom][i] = number++;
            }
            bottom--;
            for (int i = bottom; i >= top; i--) {
                arr[i][left] = number++;
            }
            left++;
        }
        return arr;
    }
}
最后修改:2022 年 05 月 25 日 02 : 07 PM
赏杯咖啡喝 谢谢您~