package NCexercise.E40;

import org.junit.Test;

import java.util.ArrayList;

public class NC38 {
@Test
public void test() {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
ArrayList<integer> list = spiralOrder(matrix);
System.out.println(list);
}</integer>

public ArrayList<Integer> spiralOrder(int[][] matrix) {
    ArrayList<Integer> res = new ArrayList<>();
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
        return res;
    }
    int m = matrix.length;//m行
    int n = matrix[0].length;//n列

    int left = 0;
    int right = n - 1;
    int top = 0;
    int bottom = m - 1;

    //边界条件:right == n/2  left == n/2-1
    //        bottom == n/2 top == n/2-1
    int temp = 0;
    while (right >= n / 2 && left <= n / 2 && bottom >= m / 2 && top <= m / 2) {
        //向右走
        for (int i = left; i <= right; i++) {
            temp = matrix[top][i];
            res.add(temp);
        }
        top++;
        if (top > bottom) {
            break;
        }
        //向下走
        for (int i = top; i <= bottom; i++) {
            temp = matrix[i][right];
            res.add(temp);
        }
        right--;
        if (right < left) {
            break;
        }
        //向左走
        for (int i = right; i >= left; i--) {
            temp = matrix[bottom][i];
            res.add(temp);
        }
        bottom--;
        if (top > bottom) {
            break;
        }
        //向上走
        for (int i = bottom; i >= top; i--) {
            temp = matrix[i][left];
            res.add(temp);
        }
        left++;
    }

    return res;
}

}