package com.zmz.algorithm.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 张明泽
 * Create by 2022/5/23 17:14
 * 螺旋矩阵一
 * LeetCode-54
 */
public class SpiralMatrix {
    public static void main(String[] args) {
        int[][] arr = new int[][]{{7,9,6}};
        List list = matrix(arr);
        System.out.println(list);
    }
    public static List<Integer> matrix(int[][] arr) {
        List<Integer> list = new ArrayList<>(arr.length * arr[0].length);
        int left = 0;
        int right = arr[0].length - 1;
        int top = 0;
        int bottom = arr.length - 1;
        while (left <= right && bottom >= top) {
            for (int i = left; i <= right; i++) {
                list.add(arr[left][i]);
            }
            top++;
            for (int i = top; i <= bottom; i++) {
                list.add(arr[i][right]);
            }
            right--;
            // [7,9,6] 第二个条件不加这个会错误
            for (int i = right; i >= left && top <= bottom; i--) {
                list.add(arr[bottom][i]);
            }
            bottom--;
            // [7],[9],[6] 第二个条件不加这个会错误
            for (int i = bottom; i >= top; i--) {
                list.add(arr[i][left]);
            }
            left++;
        }
        return list;
    }
}
最后修改:2022 年 05 月 25 日 02 : 06 PM
赏杯咖啡喝 谢谢您~