题目:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix =
[
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100
题解:
根据四个边界来遍历,从左到右,从上到下,从右到左,从下到上。
public class Solution
{
public int[] SpiralOrder(int[][] matrix)
{
if(matrix.Length == 0)
{
return new int[0];
}
int l = 0,r = matrix[0].Length -1,t = 0,b = matrix.Length-1,x= 0;
int[] result = new int[(r+1)*(b+1)];
while(t <= b && l <= r)
{
//left -> right
for(int j = l;j<= r;j++)
{
result[x++] = matrix[t][j];
}
t++;
//top -> bottom
for(int i = t;i <= b;i++)
{
result[x++] = matrix[i][r];
}
r--;
//right -> left
for(int j = r; j >= l && t <= b;j--)
{
result[x++] = matrix[b][j];
}
b--;
//bottom -> top
for(int i = b;i >= t && l<= r;i--)
{
result[x++] = matrix[i][l];
}
l++;
}
return result;
}
}