# 顺时针打印矩阵

0 <= matrix.length <= 100
0 <= matrix[i].length <= 100

package LeetcCode.顺时针打印矩阵;

import java.util.List;

public class SpiralOrder {

public static void main(String[] args) {
int[][] matrix = new int[][]{
{1,2,0,3},
{2,33,3,6},
{2,3,0,7},
{1,4,7,9}};
SpiralOrder spiralOrder0 = new SpiralOrder();

for (int i : spiralOrder0.spiralOrder0(matrix)) {
System.out.print(i);

}System.out.println();
Solution solution = new Solution();
for (int i : solution.spiralOrder(matrix)) {
System.out.print(i);
}
}
public int[] spiralOrder0(int[][] matrix){//自写第二遍
int h = matrix.length;
if (h == 0) {//考虑输入空
return new int[0];
}
int l = matrix[0].length;
int up = 0, down = h-1, left = 0, right = l-1;
int[] res = new int[h * l];
int idx = 0;

while (true){
for (int col = left; col <= right; ++col) {
res[idx++]=matrix[up][col];
}
if (++up>down){
break;
}
for (int row = up; row <= down; ++row) {
res[idx++]=matrix[row][right];
}
if (--right<left){
break;
}
for (int col = right; col >= left; --col) {
res[idx++]=matrix[down][col];
}
if (--down<up){
break;
}
for (int row = down; row >= up; --row) {//左
res[idx++]=matrix[row][left];
}
if (++left > right) {
break;
}
}
return res;
}
public int[] spiralOrder(int[][] matrix) {//第一遍没做出来，少用a1,i1这样的变量，头晕

int n = matrix.length;
int[] a = new int[n*n];//还把给定数组想成n*n的了，阿巴阿巴
int j = n;
int flag = -1;
for (int i = 0; i < n; i++) {//第一行
a[i] = matrix[0][i];
}
for (int i = n-1; i>0; i--){//大循环次数
flag = -1*flag;
if (flag == 1){
for (int i1 = n-i; i1 <= i; i1++) {
a[j] = matrix[i1][i];           //a[j++]代替这里的结构，简单明了
j++;
}
for (int i1 = i-1; i1 >= n-i; i1--) {
a[j] = matrix[i][i1];
j++;
}
}else {
for (int i1 = i; i1 > n-i; i1--) {
a[j] = matrix[i1][n-1-i];
j++;
}
for (int i1 = n-i; i1 <= i; i1++) {
a[j] = matrix[i][i1];
j++;
}
}
}
return a;
}
}
class Solution {//默默搬运大佬代码，呜呜呜
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix.length == 0) {
return res;
}
//切蛋糕，从上下左右四个方向切，设置四个变量对应上下左右的边界值，每次切完，检查边界是否重合
//难点在于这些变量的逻辑关系变化
int up = 0, down = matrix.length - 1, left = 0, right = matrix[0].length - 1;
while (true) {
//关于for循环的++i：其实和i++效果没有差别，但是++i效率略高，原因如下
//Java中i++语句是需要一个临时变量取存储返回自增前的值，而++i不需要。
// 这样就导致使用i++时系统需要先申请一段内存空间，然后将值赛如进去，最后不用了才去释放
for (int col = left; col <= right; ++col) {//上：第一行
}
if (++up > down) {
break;
}
for (int row = up; row <= down; ++row) {//右：右边第一列
}
if (--right < left) {
break;
}
for (int col = right; col >= left; --col) {//下
}
if (--down < up) {
break;
}
for (int row = down; row >= up; --row) {//左
}
if (++left > right) {
break;
}
}
return res;
}
}


02-23 47

12-02 30
11-08 1906
05-03 171
07-07 256
10-26 169
03-17 173
04-23 2102
07-24 2202