SpiralMatrix:

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].

算法分析:其实就是两重循环遍历,每次都是遍历一圈,然后遍历里面一圈...,需要记录m,n,每次遍历后,m,n都减去2;还要记录坐标x,y;

特例是n=1;m=1;其实m,n为奇数才有这种特例。

public class SpiralMatrix
{
public List<Integer> spiralOrder(int[][] matrix)
{
List<Integer> res = new ArrayList<>();
if(matrix.length == 0 || matrix == null)
{
return res;
}
int m = matrix.length;
int n = matrix[0].length;//得先判断矩阵是否为空,否则数组下标越界
int x = 0, y = 0;
while(m > 0 && n > 0)
{
if(m == 1)
{
for(int i = 0; i < n; i ++)
{
res.add(matrix[x][y++]);
}
break;//别忘了break
}
else if(n == 1)
{
for(int j = 0; j < m; j ++)
{
res.add(matrix[x++][y]);
}
break;
} for(int i = 0; i < n-1; i ++)
{
res.add(matrix[x][y++]);
}
for(int i = 0; i < m-1; i ++)
{
res.add(matrix[x++][y]);
}
for(int i = 0; i < n-1; i ++)
{
res.add(matrix[x][y--]);
}
for(int i = 0; i < m-1; i ++)
{
res.add(matrix[x--][y]);
}
x++;
y++;
m -= 2;
n -= 2;
}
return res;
}
}

SpiralMatrix2:

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

算法分析:和上一算法,类似,只不过这是个n*n矩阵,其实可以延伸到m*n矩阵。n*n使清空更简单,特别是n=1的时候。

public class SpiralMatrix2
{
public int[][] generateMatrix(int n)
{
int[][] res = new int[n][n];
if(n == 0)
{
return res;
}
int x = 0, y = 0;
int val = 1;
while(n > 0)
{
if(n == 1)
{
res[x][y] = val;
break;
}
for(int i = 0; i < n-1; i ++)
{
res[x][y++] = val;
val ++;
}
for(int i = 0; i < n-1; i ++)
{
res[x++][y] = val;
val ++;
}
for(int i = 0; i < n-1; i ++)
{
res[x][y--] = val;
val ++;
}
for(int i = 0; i < n-1; i ++)
{
res[x--][y] = val;
val ++;
}
x ++;
y ++;
n -= 2;
}
return res;
}
}
05-28 23:44