题目来源:Leeicode
Given an integer
n, generate a square matrix filled with elements from 1 to
n
2 in spiral order.
For example,
Given n =3,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
public class Solution {
/*
按照逆时针顺序一层一层往里添加
*/
public int[][] generateMatrix(int n) {
if(n<=0)
return new int[][]{};
int a[][]=new int[n][n];
int temp=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++)
a[top][i] = temp++;
for (int i = top + 1; i <=bottom; i++)
a[i][right] = temp++;
for (int i = right - 1; i >= left; i--)
a[bottom][i] = temp++;
for (int i = bottom - 1; i > top; i--)
a[i][left] = temp++;
left++;
right--;
top++;
bottom--;}
if (n%2==1)
a[n/2][n/2]=temp;
return a;
}
}
II
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ls=new ArrayList<>();
if (matrix.length==0)
return ls;
int rows=matrix.length;
int cols=matrix[0].length;
int firstrow=0;int lastrow=rows;int firstcol=0;int lastcol=cols;
int i=0;
while (i<(Math.min(rows,cols)+1)/2){
lastrow=rows-i-1;//每一圈的最后一行
lastcol=cols-i-1;
if (i==lastrow)
for (int j=i;j<=lastcol;j++)
ls.add(matrix[i][j]);
else if (i==lastcol)
for(int j=i;j<=lastrow;j++)
ls.add(matrix[j][i]);
else{//每一圈第一行
for (int j=i;j<=lastcol;j++){
ls.add(matrix[i][j]);
}
//每一圈最后一列
for (int j=i+1;j<=lastrow;j++)
ls.add(matrix[j][lastcol]);
//每一圈最后一行
for (int j=lastcol-1;j>=i;j--)
ls.add(matrix[lastrow][j]);
//每一圈第一列
for (int j=lastrow-1;j>i;j--)
ls.add(matrix[j][i]);
}
i++;
}
return ls;
}