LeetCode(中等)螺旋矩阵(c#)

题目 为给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
在这里插入图片描述
如图所示,当一个
[1,2,3,4]
[5,6,7,8]
[9,10,11,12]
[13,14,15,16]
数组结构为该类型时
其变换规律类似于画一个长方体,第一个横右至左 为
[00] [10][20][30]
第二个笔画为,右至下
[31] [32][33]
第三个笔画为 右至左
[23] [13][03]
第四笔为左向上
[02] [01]
之后就的结构就相当于再走一遍上方的循环,直至便利所有数组结束。理解了思路,我的代码如下

public static int[] SpiralOrder(int[][] matrix)
        {
            if (matrix.Count() == 0)
            {
                return new int[0];
            }
            int x = matrix[0].Count();
            int y = matrix.Count();
            int max = x * y;
            int[] res = new int[x * y];
            int w = x;
            int h = y;
            int t1 = 0;
            int t2 = 0;
            int Rows = 0;
            for (int i = 0; i < x * y;)
            {
                for (; t1 < w; t1++)
                {
                    if (i == max)
                    {
                        return res;
                    }
                    res[i] = matrix[t2][t1];
                    i++;
                }
                t1--;
                t2++;
                for (; t2 < h; t2++)
                {
                    if (i == max)
                    {
                        return res;
                    }
                    res[i] = matrix[t2][t1];
                    i++;
                }
                t1--;
                t2--;
                for (; t1 >= Rows; t1--)
                {
                    if (i == max)
                    {
                        return res;
                    }
                    res[i] = matrix[t2][t1];
                    i++;
                }
                Rows++;
                t2--;
                t1++;
                for (; t2 >= Rows; t2--)
                {
                    if (i == max)
                    {
                        return res;
                    }
                    res[i] = matrix[t2][t1];
                    i++;
                }
                t2++;
                t1++;
                w--;
                h--;
            }
            return res;
        }

注意,之所以for循环外还要对t2或t1进行+1、-1的操作,因为for循环的最后一次循环还是对t1,t2操作了,但却没有执行,所以要对t1、t2进行恢复。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值