第九篇 C#实现螺旋矩阵

时间:2023-12-18 08:39:56
C#语言,二维数组的用法和C++、java不同 其它两种也写了,差别不大这里不上传了
using System;

namespace _NetRectangle
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var rd = new Random();

            int r = rd.Next(10);
            int n = r + 1;
            int j = 0;
            int[,] rec = new int[10,10];
            Console.WriteLine("生成的随机数是:" + r);
            while (j <= r/2)
            {
                //第一次输出最左边的数字
                for (int i = j; i <= r - j; i++)
                {
                    if (j == 0)
                    {
                        rec[i,j] = i + 1;
                    }
                    else
                    {
                        rec[i,j] = rec[i - 1,j] + 1;
                    }
                }
                //第二次输出最下边的数字
                for (int i = j + 1; i <= r - j; i++)
                {
                    rec[r - j,i] = rec[r - j,i - 1] + 1;
                }
                //第三次输出最右边的数字
                for (int i = r - j - 1; i >= j; i--)
                {
                    rec[i,r - j] = rec[i + 1,r - j] + 1;
                }

                for (int i = r - j; i > j + 1; i--)
                {
                    rec[j,i - 1] = rec[j,i] + 1;
                }
                j++;
            }

            for (int i = 0; i < n; i++)
            {
                for (int k = 0; k < n; k++)
                {
                   Console.Write(rec[i,k] + " ");
                }
                Console.WriteLine("");
            }
            Console.Read();
        }
    }
}