题目 为给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
如图所示,当一个
[1,2,3,4]
[5,6,7,8]
[9,10,11,12]
[13,14,15,16]
数组结构为该类型时
其变换规律类似于画一个长方体,第一个横右至左 为
[00] [10][20][30]
第二个笔画为,右至下
[31] [32][33]
第三个笔画为 右至左
[23] [13][03]
第四笔为左向上
[02] [01]
之后就的结构就相当于再走一遍上方的循环,直至便利所有数组结束。理解了思路,我的代码如下
public static int[] SpiralOrder(int[][] matrix)
{
if (matrix.Count() == 0)
{
return new int[0];
}
int x = matrix[0].Count();
int y = matrix.Count();
int max = x * y;
int[] res = new int[x * y];
int w = x;
int h = y;
int t1 = 0;
int t2 = 0;
int Rows = 0;
for (int i = 0; i < x * y;)
{
for (; t1 < w; t1++)
{
if (i == max)
{
return res;
}
res[i] = matrix[t2][t1];
i++;
}
t1--;
t2++;
for (; t2 < h; t2++)
{
if (i == max)
{
return res;
}
res[i] = matrix[t2][t1];
i++;
}
t1--;
t2--;
for (; t1 >= Rows; t1--)
{
if (i == max)
{
return res;
}
res[i] = matrix[t2][t1];
i++;
}
Rows++;
t2--;
t1++;
for (; t2 >= Rows; t2--)
{
if (i == max)
{
return res;
}
res[i] = matrix[t2][t1];
i++;
}
t2++;
t1++;
w--;
h--;
}
return res;
}
注意,之所以for循环外还要对t2或t1进行+1、-1的操作,因为for循环的最后一次循环还是对t1,t2操作了,但却没有执行,所以要对t1、t2进行恢复。