0
点赞
收藏
分享

微信扫一扫

54. 螺旋矩阵

乱世小白 2022-03-16 阅读 83

力扣icon-default.png?t=M276https://leetcode-cn.com/problems/spiral-matrix/


//模拟
public class Solution {
    public IList<int> SpiralOrder(int[][] matrix) {
        List<int> list=new List<int>();
        if(matrix==null||matrix.Length==0||matrix[0].Length==0) return list;
        int left=0;
        int right=matrix[0].Length-1;
        int top=0;
        int bottom=matrix.Length-1;
        int count=matrix.Length*matrix[0].Length;
        while(count>=1){
            //从左到右→
            //行不变列变
            for(int i=left;i<=right&&count>=1;i++){
                list.Add(matrix[top][i]);
                count--;
            }
            top++;
            //从上到下↓
            //列不变行变
            for(int i=top;i<=bottom&&count>=1;i++){
                list.Add(matrix[i][right]);
                count--;
            }
            right--;
            //从左到右←
            //行不变列变
            for(int i=right;i>=left&&count>=1;i--){
                list.Add(matrix[bottom][i]);
                count--;
            }
            bottom--;
            //从下到上↑
            //列不变行变
            for(int i=bottom;i>=top&&count>=1;i--){
                list.Add(matrix[i][left]);
                count--;
            }
            left++;
        }
        return list;
    }
}
举报

相关推荐

0 条评论