Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
示例 3:
输入:
[
[1]
]
输出: [1]
示例 4:
输入:
[
[2, 3, 4],
[5, 6, 7],
[8, 9, 10],
[11, 12, 13]
]
输出: [2,3,4,7,10,13,12,11,8,5,6,9]
public class Solution
{
public IList<int> SpiralOrder(int[][] matrix)
{
IList<int> result = new List<int>();
if (matrix == null || matrix.Length == 0)
return result;
int start = 0;
int end1 = matrix[start].Length - 1 - start;
int end2 = matrix.Length - 1 - start;
// 只有横着的情况
if (start == end2)
{
LeftToRight(start, end1, start, matrix, result);
return result;
}
//只有竖着的情况
if (start == end1)
{
TopToBottom(start, end2, start, matrix, result);
return result;
}
while (start < end1 && start < end2)
{
LeftToRight(start, end1, start, matrix, result);
TopToBottom(start + 1, end2, end1, matrix, result);
RightToLeft(end1 - 1, start, end2, matrix, result);
BottomToTop(end2 - 1, start + 1, start, matrix, result);
start++;
end1 = matrix[start].Length - 1 - start;
end2 = matrix.Length - 1 - start;
}
// 只剩下横着的情况
if (start == end2)
{
LeftToRight(start, end1, start, matrix, result);
}
else if (start == end1)
{
//只剩下竖着的情况
TopToBottom(start, end2, start, matrix, result);
}
return result;
}
private void LeftToRight(int start, int end, int rowIndex, int[][] matrix, IList<int> lst)
{
for (int i = start; i <= end; i++)
{
lst.Add(matrix[rowIndex][i]);
}
}
private void TopToBottom(int start, int end, int colIndex, int[][] matrix, IList<int> lst)
{
for (int i = start; i <= end; i++)
{
lst.Add(matrix[i][colIndex]);
}
}
private void RightToLeft(int start, int end, int rowIndex, int[][] matrix, IList<int> lst)
{
for (int i = start; i >= end; i--)
{
lst.Add(matrix[rowIndex][i]);
}
}
private void BottomToTop(int start, int end, int colIndex, int[][] matrix, IList<int> lst)
{
for (int i = start; i >= end; i--)
{
lst.Add(matrix[i][colIndex]);
}
}
}
1. “数组”类算法
2. “链表”类算法
3. “栈”类算法
4. “队列”类算法
5. “递归”类算法
6. “字符串”类算法
7. “树”类算法
8. “哈希”类算法
9. “搜索”类算法
10. “动态规划”类算法
11. “回溯”类算法
11. “数值分析”类算法