Appearance
29-顺时针打印矩阵
题目描述
https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
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
注意:本题与主站 54 题相同:https://leetcode.cn/problems/spiral-matrix/
思路分析
模拟法,上下左右都设定好区间,然后按照顺序打印
设定边界法:https://leetcode.cn/problems/spiral-matrix-ii/solution/spiral-matrix-ii-mo-ni-fa-she-ding-bian-jie-qing-x/ 这个解法有个小问题,注意如果数组不是正方形的需要考虑边界 输入: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]
不处理边界break的话可能会输出一下,即最后多输出一个6 [1,2,3,4,8,12,11,10,9,5,6,7,6]
原因是,
1 2 3 4 5 6 7 8 9 10 11 12
最后一圈从左到右 输出 5,6,7 之后,top+1 = 2 此时 bottom 为1,应该后续没有输出了。 但是因为循环体里面还在继续,所以 right to left 又会执行一次, 就输出了 6 因此每次操作过边界之后,判断一下是否已经越界,如果越界那可以直接 break 了.
实现代码
csharp
public class Solution {
public int[] SpiralOrder(int[][] matrix) {
List<int> result = new List<int>();
if(matrix.Length == 0){
return result.ToArray();
}
int left = 0;
int top = 0;
int right = matrix[0].Length - 1;
int bottom = matrix.Length - 1;
while(left <= right && top <= bottom ){
for(int i=left; i<=right; i++){
result.Add(matrix[top][i]);
}
top++;
if(top > bottom){
break;
}
for(int i=top; i<=bottom; i++){
result.Add(matrix[i][right]);
}
right--;
if(right < left){
break;
}
for(int i=right; i>=left; i--){
result.Add(matrix[bottom][i]);
}
bottom--;
if(bottom < top){
break;
}
for(int i=bottom; i>=top; i--){
result.Add(matrix[i][left]);
}
left++;
}
return result.ToArray();
}
}
AlgoPress