LeetCode -- SpiralOrder
题目描述:
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].
从例子可以看出,需要做的是从矩阵的第一个元素为起始,沿外环向内依次遍历,最后打印出结果。
思路:
获取矩阵的长宽,设需要走n圈,则n = Min(宽度,高度)/2。
从左上节点为起始开始遍历,走到最右的最后一个元素开始向下走,走到最后向左走,最后向上走。走了一圈,需要把坐标往内+1。
需要考虑刚好处于矩阵中间线的情况。
实现代码:
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].
从例子可以看出,需要做的是从矩阵的第一个元素为起始,沿外环向内依次遍历,最后打印出结果。
思路:
获取矩阵的长宽,设需要走n圈,则n = Min(宽度,高度)/2。
从左上节点为起始开始遍历,走到最右的最后一个元素开始向下走,走到最后向左走,最后向上走。走了一圈,需要把坐标往内+1。
需要考虑刚好处于矩阵中间线的情况。
实现代码:
public class Solution {
public IList<int> SpiralOrder(int[,] matrix) {
if(matrix == null){
return new List<int>();
}
var result = new List<int>();
var rowLen = matrix.GetLength(0);
var len = matrix.GetLength(1);
if(rowLen == 1){
for(var i =0 ;i < len; i++){
result.Add(matrix[0,i]);
}
return result;
}
if(len == 1){
for(var i =0 ;i < rowLen; i++){
result.Add(matrix[i,0]);
}
return result;
}
var minLen = Math.Min(rowLen,len);
var cycleCount = minLen % 2 == 0 ? minLen/2 : (minLen + 1) / 2;
var c = 0;
for(var i = 0;i < cycleCount; i++){
if(c == len-c-1){
for(var k = c;k < rowLen - c; k++){
result.Add(matrix[k, c]);
}
c++;
continue;
}
// stick row to top, column : [c,len-c-1]
for(var top = c; top < len-c - 1; top++){
result.Add(matrix[c,top]);
}
// stick column to right, row : [c,rowLen-c-1]
for(var right = c; right < rowLen-c - 1; right ++){
result.Add(matrix[right, len-c-1]);
}
// stick row to bottom, column : [len-c-1, c]
for(var down = len-c -1; down > c; down --){
result.Add(matrix[rowLen-c-1, down]);
}
// stick column to left, row : [len-c-1, c]
for(var left = rowLen-c - 1; left > c; left --){
result.Add(matrix[left, c]);
}
c++;
}
return result;
}
}