Leetcode 螺旋矩阵 -java

 
 

矩阵分圈处理

  

最外圈 

内圈

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

public class 转圈打印矩阵 {
   public static void main(String[] args) {
    int a [] [] = {{1,2,3},{4,5,6},{7,8,9}};
//    int a [][] = {{1,2,3,4}};
    System.out.println(spiralOrder(a));
}
   public static List<Integer> spiralOrder(int[][] matrix) {
	   List<Integer> a = new ArrayList<>();
	   int x=0,y=0;
	   int m=matrix.length-1;
	   int k = 0;
	   //判断数组是不是为空,不判断直接 k=matrix[0].length-1,就会越界。
	   if (matrix.length==0&&matrix!=null) {
		return a;
	}else {
		 k=matrix[0].length-1;
	}
	   
	   while (x<=m&&y<=k) {
		   //如果只有一行
	    if (x==m) {
			for (int i = y; i <=k; i++) {
				a.add(matrix[x][i]);
			}
		}
           //如果只有一列
	    else if (y==k) {
			for (int i = x; i<=m; i++) {
				a.add(matrix[i][y]);
			}
		}else {
			int x0=x,y0=y;
			while (y0!=k) {   //上边
				a.add(matrix[x][y0]);
			    y0++;
			}
			while (x0!=m) {  //右边
				a.add(matrix[x0][k]);
				x0++;
			}
		   while (y0!=y)  {  //下边
			a.add(matrix[m][y0]);
			y0--;
		   }
		   while (x0!=x) {    //左边
			a.add(matrix[x0][y]);
			x0--;
		}
       }
	    //矩阵分圈,进入下一圈。
	    x++;
	    y++;
	    m--;
	    k--;
	   }	   
	return a;
   }
}

猜你喜欢

转载自blog.csdn.net/ZZQzzq123456/article/details/80381177